Last active
September 9, 2021 09:55
-
-
Save ofstudio/e13276a9c587ecd41a95 to your computer and use it in GitHub Desktop.
Couple useful heplers for ghost
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
This code is compatible with
ghost 0.7.4
and support multiple tags.