繁体   English   中英

在嵌套的车把循环中使用索引

[英]Using indexes in nested Handlebar's loops

我正在尝试创建下表。

在此处输入图片说明

我已经将o传递给车把(PS。我可以重新构造该对象。应该吗?)。

var o={
years:[1800,1900,2012],
countries:["Africa","America","Asia","Europe","Oceania"],
data:[
  [107,133,1052],
  [null,156,954],
  [635,null,4250],
  [203,408,740],
  [2,6,38]
  ]
};

根据http://handlebarsjs.com/builtin_helpers.html的介绍 ,我可以通过{{@index}}访问该索引。 但是,由于我有两个循环,如何访问两个循环,以获得正确的数据?

<table>
    <thead>
        <tr> 
            <th></th> 
            {{#each years}} {{!-- is "#each years" and "#years" the same thing??? --}} 
            <th>{{this}}</th> 
            {{/each}} 
        </tr> 
    </thead> 
    <tbody> 
        {{#each countries}} 
        <tr> 
        <td>{{this}}</td> 
        {{#each data}} 
        <tr> 
            <td>{{this}}????</td> 
        </tr> 
        {{/each}} 
        </tr> 
        {{/each}} 
    </tbody> 
</table>

首先{{#each years}} 都会有相同的结果作为{{#years}} 后一种形式来自Mustache ,是库所称的Section Handlebars文档解释了Handlebars块表达式和Mustache Sections之间区别

您无法在{{#each countries}}循环中使用{{#each data}}的原因是因为{{#each countries}}循环中的数据上下文是当前国家/地区迭代。 您必须达到父级作用域才能访问data对象。 这是通过Handlebars路径完成的,将被写为{{../data}}

但是,在我们的场景中,我们希望获取特定data元素,其索引与我们当前国家/地区迭代的索引匹配。 为此,我们可以使用查找助手 结果将如下所示:

<table>
    <thead>
        <tr> 
            <th></th> 
            {{#each years}}
                <th>{{this}}</th> 
            {{/each}} 
        </tr> 
    </thead> 
    <tbody> 
        {{#each countries}} 
            <tr> 
                <td>{{this}}</td> 
                {{#each (lookup ../data @index)}} 
                    <tr> 
                        <td>{{this}}</td> 
                    </tr> 
                {{/each}} 
            </tr> 
        {{/each}} 
    </tbody> 
</table>

暂无
暂无

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

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