javascript Handlebars.js - 使用可变键访问对象值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19646244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:19:48  来源:igfitidea点击:

Handlebars.js - Access object value with a variable key

javascripthandlebars.js

提问by Kevin Wang

Looking for a way to access to achieve this:

寻找一种访问方式来实现这一目标:

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

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

如何评估 的值,this然后将其作为对象的键进行引用otherObject

回答by Mario Negrete

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

通过查找:http: //handlebarsjs.com/builtin_helpers.html#lookup

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

回答by Fabricio c Zuardi

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