Handlebars.js - Access object value with a variabl

2020-06-30 10:03发布

问题:

Looking for a way to access to achieve this:

{{#each someArray}}
  {{../otherObject.[this]}}
{{/each}}

How do I evaluate the value of this and then reference it as a key to my object otherObject?

回答1:

With lookup: http://handlebarsjs.com/builtin_helpers.html#lookup

{{#each someArray}}
  {{lookup ../otherObject this}}
{{/each}}


回答2:

One possible solution with a helper:

/*
{{#each someArrayOfKeys}}
  {{#withItem ../otherObject key=this}}
    {{this}}
  {{/withItem}}
{{/each}}
*/

Handlebars.registerHelper('withItem', function(object, options) {
    return options.fn(object[options.hash.key]);
});