无法在带车把的多维数组中循环

Cannot loop through multidimensional array with handlebars

本文关键字:数组 循环      更新时间:2023-09-26

查看我的数据:

data: {
    content: [
    [
    "School Name",
    "Location",
    "Type",
    "No. eligible pupils",
    "Average points per student",
    "Average points per exam entry",
    "% obtaining two facilitating subjects"
    ],
    [
    "Colchester Royal Grammar School",
    "Colchester",
    "State",
    "349",
    "1428",
    "263.3",
    "77%"
    ], and so on...
 ]
}

我正在尝试遍历这个数组数组,以创建一个表。因此,对于每个数组,我需要将其包装在<tr></tr>中,对于每个数组中的每个元素,我需要将其包装在<td></td>中。我还需要区分第一行以使用<thead><th>,但目前我正试图了解正确的结构。

我的代码所做的是只创建一个包含整个事物的<td>,而不是多个<tr><td>

        {{#each data.content}}
            <tr>
                {{#each this}}
                    <td>{{ this }}</td>
                {{/each}}
            </tr>
        {{/each}}
不能

直接使用模板中的数据。因为要将数据对象传递给已编译的模板 function.so 所以应该使用它来引用当前上下文。

最好使用块参数以避免更多此引用。这将使代码更难理解

没有块参数

{{#each this.content}} 
     <tr>
        {{#each this}} 
            <td>{{ this }}</td> 
        {{/each}} 
     </tr>
 {{/each}}

通过使用块参数,

{{#each this.content as | rowKey, row |}} 
         <tr>
            {{#each row as | colKey, column|}} 
                <td>{{ column }}</td> 
            {{/each}} 
         </tr>
 {{/each}}

当模板变大时,它具有更多优势