javascript - Handlebars.js - Global Contexts - Stack Overflow

Say I have a static list of users cached somewhere in my application like App.Users. I'll probably

Say I have a static list of users cached somewhere in my application like App.Users. I'll probably have the need to list my users in several dozen places in my application. Conventionally, I'll just need to pass my list in with my context to the template.

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

var html = tmpl({
    model: model,
    users: App.Users
});

But this approach requires some wiring in both the template and the javascript. What I would like to do is specify this in the template alone so I don't need to remember this in my scripts. Consider something like this...

{{#each {{users}}}}
    <li> ... </li>
{{/each}}

...Where users is a helper function that just returns my App.Users. Wouldn't that be nice?

So that totally doesn't pile. What is another solution?

Say I have a static list of users cached somewhere in my application like App.Users. I'll probably have the need to list my users in several dozen places in my application. Conventionally, I'll just need to pass my list in with my context to the template.

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

var html = tmpl({
    model: model,
    users: App.Users
});

But this approach requires some wiring in both the template and the javascript. What I would like to do is specify this in the template alone so I don't need to remember this in my scripts. Consider something like this...

{{#each {{users}}}}
    <li> ... </li>
{{/each}}

...Where users is a helper function that just returns my App.Users. Wouldn't that be nice?

So that totally doesn't pile. What is another solution?

Share asked Sep 17, 2013 at 17:19 savingersavinger 6,7449 gold badges42 silver badges58 bronze badges 2
  • possible duplicate of Global variables in Handlebars if blocks – Evan Davis Commented Sep 17, 2013 at 17:59
  • Let me know if that's not what you had in mind, but it seems like the same question. – Evan Davis Commented Sep 17, 2013 at 17:59
Add a ment  | 

1 Answer 1

Reset to default 7

Went with an abstract helper function deal... which let's be honest, seems to be the solution to 99% of Handlebars questions.

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

And used in an example...

{{#global "Users"}}
    {{#each this}}
         <th>{{Name}}</th>
    {{/each}}
{{/global}}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745070405a4609508.html

相关推荐

  • javascript - Handlebars.js - Global Contexts - Stack Overflow

    Say I have a static list of users cached somewhere in my application like App.Users. I'll probably

    3小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信