Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to register a helper for a single handlebars template?

I would like to create a handlebars template and use a local helper for just that single template. I know how to use Handlebars.registerHelper to register helpers for all templates, but I only need this for the local template. (something similar to what ExtJS supports with XTemplates)

For example something like this based upon handlebars.js documentation:

var context = { posts: [{url: "/hello-world", body: "Hello World!"}] };
var source = "<ul>{{#posts}}<li>{{{link_to this}}}</li>{{/posts}}</ul>"

var template = Handlebars.compile(source, {
   link_to: function(context) {
       return "<a href='" + context.url + "'>" + context.body + "</a>";
   }
);
template(context);

Is this possible or do all helpers have to be registered globally?

like image 609
Allen Avatar asked Jun 27 '12 16:06

Allen


1 Answers

Use this syntax:

template(context, {helpers: helpers})

Local helpers redefine global. So if you want each, if or other registered global helpers just extend object:

helpers = $.extend({}, Handlebars.helpers, helpers);
template(context, {helpers: helpers})
like image 57
Igor Alekseev Avatar answered Nov 14 '22 03:11

Igor Alekseev