是否可以为单个车把模板注册帮助器?

时间:2012-06-27 16:17:24

标签: handlebars.js

我想创建一个把手模板,并使用本地帮助器来处理该单个模板。我知道如何使用Handlebars.registerHelper为所有模板注册帮助器,但我只需要本地模板。 (类似于ExtJS支持的XTemplates)

例如基于handlebars.js文档的这样的东西:

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);

这是可能的还是所有帮助者都必须在全球注册?

1 个答案:

答案 0 :(得分:11)

使用以下语法:

template(context, {helpers: helpers})

本地助手重新定义全球。因此,如果您想要eachif或其他已注册的全局帮助者只需扩展对象:

helpers = $.extend({}, Handlebars.helpers, helpers);
template(context, {helpers: helpers})