如何使用Handlebars.js获取索引处的数组值? [英] How to get an array value at index using Handlebars.js?

查看:681
本文介绍了如何使用Handlebars.js获取索引处的数组值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有JSON:

  {
userinput:[
{name:brian ,价值:我喜欢馅饼},
{名称:苏珊,价值:模因愚蠢}
],
反馈:[
{value:我也喜欢pies},
{value:null}
]
}

我试图画出这样的表格:

  name .. ... |输入...... |反馈
----------- | ---------------- | ---------------- -
brian |我喜欢馅饼|我也喜欢馅饼
susan | mems是愚蠢的空白

虽然我认识到将反馈作为userinput的值会更好,我有没有这样做......



我试图在{{#each userinput}}里面得到反馈的索引,例如

  {{#每个用户输入}} 
< td> {{name}}< / td>< td> {{值}}< / TD>< TD> {{../反馈[@index]。价值}}< / TD>
{{/ each}}

当然 {{ ../ feedback [@index] .value}} 不起作用。



什么是最好的方法(不改变json的结构)来获取反馈数组内匹配索引的值?

解决方案

这可以使用 查找助手


lookup 助手允许使用Handlebars变量进行动态参数解析。这对于解析数组索引的值很有用。


因此,您示例的模板如下所示:
p>

  {{#each userinput}} 
< td> {{name}}< / td>
< td> {{value}}< / td>
< td>
{{#with(lookup ../feedback @index)}}
{{value}}
{{/ with}}
< / td>
{{/ each}}


Say I have JSON:

{
userinput: [
    {name: "brian", "value": "i like pies"},
    {name: "susan", "value": "memes are stupid"}
],
feedback: [
    {value: "i also like pies"},
    {value: "null"}
]
}

And I'm trying to draw a table like this:

name ..... | input ......   | feedback
-----------|----------------|-----------------
brian      | I like pies    | I also like pies
susan      | mems are stupid| null

And while I recognise that it would be better to have feedback as a value of "userinput", what I have is not done like that ...

I'm trying to get the index of feedback inside {{#each userinput}}`, e.g.

{{#each userinput}}
<td>{{name}}</td><td>{{value}}</td><td>{{../feedback[@index].value}}</td>
{{/each}}

But of course {{../feedback[@index].value}} does not work.

What is the best way (without changing the structure of the json) to grab the value of the matching index inside the feedback array?

解决方案

This can be accomplished using the lookup helper:

The lookup helper allows for dynamic parameter resolution using Handlebars variables. This is useful for resolving values for array indexes.

So the template for your example would look like this:

{{#each userinput}}
    <td>{{name}}</td>
    <td>{{value}}</td>
    <td>
        {{#with (lookup ../feedback @index)}}
            {{value}}
        {{/with}}
    </td>
{{/each}}

这篇关于如何使用Handlebars.js获取索引处的数组值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆