How can I generate pages in Assemble based on an different json files? - assemble

So I have a folder rules that that looks like this:
rule-001.json
rule-002.json
rule-003.json
Each *.json file is of a unified format:
{ name: 'AAA', descriptions: 'BBB' }
How can I generate a pages based on these files in Assemble?

The short answer is that you need to load your JSON data in your Gruntfile and use it to replace the Assemble pages object.
I have written a blog post about generating pages from data, based on the Assemble Blog Theme sample. In both cases, the pages data was stored in a single JSON file.
In your case, you need to load the data from all of JSON files in your Gruntfile, and transform the data into the pages format. You can do this any number of ways, but one simple way would be to write a function in your Gruntfile that does this:
function loadDataPages (jsonFileSpec) {
var path = require("path");
var jsonPaths = grunt.file.expand(jsonFileSpec);
var jsonPages = jsonPaths.map(function (jsonPath) {
var jsonData = grunt.file.readJSON(jsonPath);
var outputFileName = path.basename(jsonPath, path.extname(jsonPath)) + ".html";
var jsonPage = {
"data": jsonData,
"content": "This is the body content for page " + outputFileName,
"filename": outputFileName
};
return jsonPage;
});
return jsonPages;
}
and then you need to load this data object in your Grunt config and pass it to Assemble's pages option:
grunt.initConfig({
assemble: {
data: {
options: {
flatten: true,
layout: "source/templates/layouts/custom-data-layout.hbs",
pages: loadDataPages("source/custom-data/*.json")
},
files: {
"output/custom-data-pages/": ["source/custom-data/index.hbs"]
}
}
}
// ...
});
Here is what the layouts might look like:
custom-data-layout.hbs
<!DOCTYPE html>
<html>
<head>
<title>Custom Data - {{name}}</title>
</head>
<body>
<h1>Custom Data - {{name}}</h1>
<p>{{ description }}</p>
{{> body }}
</body>
</html>
index.hbs
---
layout: false
title: Custom Data Index
---
<!DOCTYPE html>
<html>
<head>
<title>{{title}}</title>
</head>
<body>
<h1>{{title}}</h1>
<ul>
{{#each pages }}
<li>{{basename}}</li>
{{/each}}
</ul>
</body>
</html>

Something like this should work for you. You just create separate Assemble tasks and call the main Assemble task with grunt.
https://gist.github.com/davidwickman/a0bf961e3099ea6b9c35

Related

sails doesnt not auto insert dependencies with handlebars

I'm trying to use handlebars for the templating engine but sails does not seem to insert the files in the dependency folder.
/config/views.js:
engine: 'handlebars',
layout: false,
partials: false
/views/login.handlebars:
<!DOCTYPE html>
<html>
<head>
<!--STYLES-->
<!--STYLES END-->
</head>
<body>
<p>Handlebars</p>
<!--SCRIPTS-->
<!--SCRIPTS END-->
</body>
</html>
/assets/js/dependencies contains:
bootstrap.min
jquery.min
sails.io.js
When I go to the rendered page after lifting sails the files are not populated in between the scripts tag.
Thanks!!
You should update your tasks/config/sails-linker.js and replace all occurrences of ".ejs" with ".handlebars"
E.g. from:
devJs: {
options: {
startTag: '<!--SCRIPTS-->',
endTag: '<!--SCRIPTS END-->',
fileTmpl: '<script src="%s"></script>',
appRoot: '.tmp/public'
},
files: {
'.tmp/public/**/*.html': require('../pipeline').jsFilesToInject,
'views/**/*.html': require('../pipeline').jsFilesToInject,
'views/**/*.ejs': require('../pipeline').jsFilesToInject // <- HERE
}
},
to
devJs: {
options: {
startTag: '<!--SCRIPTS-->',
endTag: '<!--SCRIPTS END-->',
fileTmpl: '<script src="%s"></script>',
appRoot: '.tmp/public'
},
files: {
'.tmp/public/**/*.html': require('../pipeline').jsFilesToInject,
'views/**/*.html': require('../pipeline').jsFilesToInject,
'views/**/*.handlebars': require('../pipeline').jsFilesToInject // <-HERE
}
},
See also this page (where the original answer comes from).
https://mtjburton.co.uk/post/sailsjs+handlebarsjs/

Unable to Execute Jquery from sidebar in Addon Firefox SDK

I am new to this Firefox SDK , but what i have understood you can execute content Scripts on Pages.
Here is the Code
MAIN.JS
var tabs = require("sdk/tabs");
var data = require("sdk/self").data;
var sidebar = require("sdk/ui/sidebar").Sidebar({
id: 'my-sidebar',
title: 'My sidebar',
url: data.url("index.html"),
onReady: function (worker) {
worker.port.emit('turl',tabs.activeTab.url);
}
});
SIDEBAR.JS
$('#bt1').on('click',function(){
$('title').textContent;
});
INDEX.HTML
<!DOCTYPE HTML>
<html>
<body>
<input type="button" id="bt1" value="Click Me"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="sidebar.js"></script>
</body>
</html>
But this code tries to find out title of the Sidebar html.
I have also tried using contentScriptFile in Main.js but same thing happened
var tabs = require("sdk/tabs");
var data = require("sdk/self").data;
var sidebar = require("sdk/ui/sidebar").Sidebar({
id: 'my-sidebar',
title: 'My sidebar',
url: data.url("index.html"),
contentScriptFile: [data.url("jquery.min.js"),data.url("sidebar.js")],
onReady: function (worker) {
worker.port.emit('turl',tabs.activeTab.url);
}
});
The Jquery code is in the sidebar.js
Still no Results.Please help
There is no contentScriptFile for the Sidebar class.
Try this: copy the jquery library to a local file in the data folder, then refer to it using a relative path. Sidebars can only use 'local' JS, they cannot load scripts from the internet.

cross rider extension to fetch new posts from feed using google feeds api

I am trying to create an extension to display all the latest posts fetched from my feed using google feeds api. To implement this, I have added this code in background.js:
appAPI.ready(function() {
// Global variable to hold the toggle state of the button
var buttonState = true;
// Sets the initial browser icon
appAPI.browserAction.setResourceIcon('images/icon.png');
// Sets the tooltip for the button
appAPI.browserAction.setTitle('My Postreader Extension');
appAPI.browserAction.setPopup({
resourcePath:'html/popup.html',
height: 300,
width: 300
});});
and in popup.html,
<!DOCTYPE html><html><head><meta http-equiv="X-UA-Compatible" content="IE=edge">
<script type="text/javascript">
function crossriderMain($) {eval(appAPI.resources.get('script.js')); }</script>
</head>
<body><div id="feed"></div></body></html>
The script.js file is-
google.load("feeds", "1");
function initialize() {
var feed = new google.feeds.Feed("http://www.xxxxx.com/feed/");
feed.setNumEntries(10);
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("feed");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var div = document.createElement("div");
var link = document.createElement('a');
link.setAttribute('href', entry.link);
link.setAttribute('name', 'myanchor');
div.appendChild(document.createTextNode(entry.title));
div.appendChild(document.createElement('br'));
div.appendChild(link);
div.appendChild(document.createElement('br'));
container.appendChild(div);
}
}
});
}
google.setOnLoadCallback(initialize);
But I am unable to get desired result.The popup doesn't display anything.It just remain blank.
Since you are using a resource file for the popup's content, it's best to load the remote script from the crossriderMain function, as follows:
<!DOCTYPE html>
<html>
<head>
<!-- This meta tag is relevant only for IE -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script type="text/javascript">
function crossriderMain($) {
appAPI.db.async.get('style-css', function(rules) {
$('<style type="text/css">').text(rules).appendTo('head');
});
appAPI.request.get({
url: 'http://www.google.com/jsapi',
onSuccess: function(code) {
$.globalEval(code);
appAPI.db.async.get('script-js', function(code) {
// runs in the context of the extension
$.globalEval(code.replace('CONTEXT','EXTN'));
// Alternatively, run in context of page DOM
$('<script type="text/javascript">').html(code.replace('CONTEXT','PAGE DOM')).appendTo('head');
});
}
});
}
</script>
</head>
<body>
<h1>Hello World</h1>
<div id="feed"></div>
</body>
</html>
[Disclaimer: I am a Crossrider employee]

Auto complete with multiple keywords

I want . Auto complete text box with multiple keyword. it's from database. if I use jQuery and do operation in client side mean. If the database size is huge, it leads to some issues. I need to know how this is done on the server side and get proper result.
I have already seen this topic but the operation is done on the client side. I need it from the database directly.
<html>
<head>
<title>Testing</title>
<link href="css/jquery-ui-1.10.3.custom.css" rel="stylesheet" type="text/css" />
<style type="text/css">
.srchHilite { background: yellow; }
</style>
<script src="scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="scripts/jquery-ui-1.10.3.custom.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
NewAuto();
});
function NewAuto() {
var availableTags = ["win the day", "win the heart of", "win the heart of someone"];
alert(availableTags); // alert = win the day,win the heart of,win the heart of someone
$("#tags").autocomplete({
source: function(requestObj, responseFunc) {
var matchArry = availableTags.slice(); // Copy the array
var srchTerms = $.trim(requestObj.term).split(/\s+/);
// For each search term, remove non-matches.
$.each(srchTerms, function(J, term) {
var regX = new RegExp(term, "i");
matchArry = $.map(matchArry, function(item) {
return regX.test(item) ? item : null;
});
});
// Return the match results.
responseFunc(matchArry);
},
open: function(event, ui) {
// This function provides no hooks to the results list, so we have to trust the selector, for now.
var resultsList = $("ul.ui-autocomplete > li.ui-menu-item > a");
var srchTerm = $.trim($("#tags").val()).split(/\s+/).join('|');
// Loop through the results list and highlight the terms.
resultsList.each(function() {
var jThis = $(this);
var regX = new RegExp('(' + srchTerm + ')', "ig");
var oldTxt = jThis.text();
jThis.html(oldTxt.replace(regX, '<span class="srchHilite">$1</span>'));
});
}
});
}
</script>
</head>
<body>
<div>
<label for="tags">
Multi-word search:
</label>
<input type="text" id="tags" />
</div>
</body>
</html>
take a look to Select2 it may help you.
Select2 is a jQuery based replacement for select boxes. It supports
searching, remote data sets, and infinite scrolling of results.
link
In your code, you have provided source as array. As you mentioned in comments, problem is how to get the data to source in jquery.
To make this work,
You need to do following
load jquery in header, which is you have already done.
Provid array,string or function for the source tag. [See api for
the source tag][1]
[1]: http://api.jqueryui.com/autocomplete/#option-source
In your serverside script, provid Jason encoded string.
If you check the API, you can see they have clear mentioned this.
Here is the jquery code
$(function() {
$( "#option_val" ).autocomplete({
dataType: "json",
source: 'search.php',
minLength: 1,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
});
</script>
Here is the php code, Sorry if you use differnt serverside script language.
<?php
// Create connection
$con=mysqli_connect("localhost","wordpress","password","wordpress");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result=mysqli_query($con,"select * from wp_users");
while($row = mysqli_fetch_array($result))
{
$results[] = array('label' => $row['user_login']);
}
echo json_encode($results);
mysqli_close($con);
?>

backbone.js - problem loading using models defined in separate file

I'm running Sinatra with Backbone.js. I'm trying to split up my models, views, etc so they aren't all lumped into a single JS file. Right now I have the following.
index.html
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<script src="scripts/underscore-min.js"></script>
<script src="scripts/jquery-1.5.min.js"></script>
<script src="scripts/backbone-min.js"></script>
<script src="scripts/models.js"></script>
...
models.js
Models = {
var Event = Backbone.Model.extend({
});
var Events = Backbone.Collection.extend({
url: '/events',
model: Event
});
};
So models.js expects that Backbone.js has been loaded, which it should have been based on index.html, however, I'm getting a JavaScript error in models.js where I reference Backbone.Model.
Any ideas on what I'm missing here?
That isn't valid javascript. Something like this is more likely to work :
Models = {}
Models.Event = Backbone.Model.extend({
});
Models.Events = Backbone.Collection.extend({
url: '/events',
model: Event
});