Skip to content

Instantly share code, notes, and snippets.

@jankuca
Forked from ofstudio/heplers.js
Last active August 29, 2015 14:21
Show Gist options
  • Save jankuca/28483157bda13d0cf65c to your computer and use it in GitHub Desktop.
Save jankuca/28483157bda13d0cf65c to your computer and use it in GitHub Desktop.
var hbs = require('express-hbs'),
api = require('core/server/api'),
_ = require('lodash'),
async = require('express-hbs/lib/async'), // To redefine `registerAsyncHelper`
registerAsyncHelper;
// Redefine `registerAsyncHelper` from `express-hbs`
registerAsyncHelper = function (name, fn) {
hbs.handlebars.registerHelper(name, function (context, options) {
// Pass `[context, options]` as arg instead of `context` only
return async.resolve(fn.bind(this), [context, options]);
});
};
module.exports = function () {
// {{#node_env}} Helper
//
// Example:
// {{#node_env production}}
// ...production only
// {{/node_env}}
//
hbs.registerHelper('node_env', function (env, options) {
return (options.data.root.settings.env === env) ? options.fn(this) : options.inverse(this)
});
// {{#by_tag}} Helper
//
// Example:
// {{#by_tag 'dev'}}
// {{#foreach posts}}
// {{title}}
// {{content}}
// {{/foreach}}
// {{/by_tag}}
//
// TODO `page` or smth like this functionality
//
registerAsyncHelper('by_tag', function (context_data, callback) {
var context = context_data[0], // get context and options passed from context_data array
options = context_data[1],
parameters = (options || {}).hash || {},
request = {
context: {internal: true},
tag: context
};
if (parameters.hasOwnProperty('limit')) {
request.limit = parameters.limit
}
return api.posts.browse(request).then(function (responce) {
var data;
if (options !== undefined && typeof options.fn === 'function') {
data = hbs.handlebars.createFrame(options.data || {});
data.posts = responce.posts;
console.log(data);
callback(options.fn(data))
} else {
callback('')
}
});
});
// {{{hello_kitty}}} Sample Helper
hbs.registerHelper('hello_kitty', function () {
return new hbs.handlebars.SafeString('Hello =^oo^= Kitty!');
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment