Handlebars.js - 全球上下文

sav*_*ger 3 javascript handlebars.js

假设我在我的应用程序中的某个地方缓存了一个静态用户列表App.Users.我可能需要在我的应用程序中的几十个地方列出我的用户.按照惯例,我只需要将我的上下文列表传递给模板.

var tmpl = Handlebars.templates['TemplateName'];

var html = tmpl({
    model: model,
    users: App.Users
});
Run Code Online (Sandbox Code Playgroud)

但是这种方法需要在模板和javascript中进行一些连接.我想做的是单独在模板中指定这个,所以我不需要在我的脚本中记住这一点.考虑这样的事情......

{{#each {{users}}}}
    <li> ... </li>
{{/each}}
Run Code Online (Sandbox Code Playgroud)

... users帮助函数在哪里才能返回我的App.Users.那不是很好吗?

所以完全不编译.什么是另一种解决方案

sav*_*ger 7

与一个抽象的帮助函数交易...说实话,似乎是99%的Handlebars问题的解决方案.

Handlebars.registerHelper('global', function(context, options) {
    return options.fn(App.[context].toJSON()); // Object is Backbone Collection
})
Run Code Online (Sandbox Code Playgroud)

并用在一个例子中......

{{#global "Users"}}
    {{#each this}}
         <th>{{Name}}</th>
    {{/each}}
{{/global}}
Run Code Online (Sandbox Code Playgroud)