简体   繁体   English

把手在#each中不同对象中的一般上下文对象中达到键值对

[英]Handlebars reach a key value pair in general context object in a different object in #each

I have a template used by Handlebars and my context like below: 我有一个由Handlebars使用的模板,其上下文如下所示:

var context = {
    abc: ["a","b","c","d"],
    xyz: {
         words: {
             a: 1,
             b: 2,
             c: 3,
             d: 4
         }
    }
}
var template = Handlebars.compile(tpl);
var output = template(context);

Everything is fine till here. 一切都很好,直到这里。 But i need to do something like: 但是我需要做类似的事情:

{{#each abc }}
 <li><a data-toggle="tab" href="#{{ ../xyz.words[this] }}"> {{ this }} </a></li>
{{/each }}

I expect to gather a value given by key in xyz.words context but I get nothing. 我希望收集xyz.words上下文中的键给定的值,但我什么也没得到。 Instead, if I use only {{ this }} it works fine and return a value from abc. 相反,如果我仅使用{{ this }}它将正常工作并从abc返回一个值。

What am I missing here? 我在这里想念什么?

Edit: 编辑:

By the way I tried to use Helpers and here is what I did: 顺便说一句,我尝试使用助手,这是我所做的:

Handlebars.registerHelper("whatis", function(key){
       return  xyz.words[key];
    });

{{#each abc }}
 <li><a data-toggle="tab" href="#{{ whatis this] }}"> {{ this }} </a></li>
{{/each }}

You need to create a helper in order to access the object with a dynamic, variable-based key (running example) : 您需要创建一个帮助程序,以便使用基于变量的动态键访问对象(运行示例)

Template: 模板:

{{#each abc }}
 <li> 
     {{#getObjectValue ../xyz.words key=this}}
     <a data-toggle="tab" href="#{{this}}">
     {{/getObjectValue}}
     {{ this }} </a>
 </li>
{{/each }}

Code: 码:

Handlebars.registerHelper('getObjectValue', function(object, options) {
    return options.fn(object[options.hash.key]);
});
var template = Handlebars.compile($("#template").html());
$("#target").html(template(context));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM