1

我正在尝试使用对象的属性进行迭代,以动态打印一个表,该表具有一个带有属性的数组和一个带有每个属性值的对象。

我不知道如何使用来自车把的 hbs express 进行 2 次迭代

people: [{
    name: "ken",
    lastname: "grace",
    age: 10
},
{
    name: "ron",
    lastname: "bond",
    age: 20
}];

properties = ["name","lastname", "age"];

HTML 代码:

<table>
                        <thead>
                            <tr>
                                {{#each properties as |property index|}}
                                    <th>
                                        <span>{{property}}</span>
                                    </th>
                                {{/each}}
                            </tr>
                            
                        </thead>
                        <tbody>
                            {{#each people}}
                                <tr>
                                    {{#each properties}}
                                        <th>
                                            {{!-- trying something like: --}}
                                            {{!-- {{people.property}} --}}
                                        </th>
                                    {{/each}}
                                </tr>
                            {{/each}}
                        </tbody>
                    </table>
4

1 回答 1

0

正如用户@76484提到的,您想使用内置的lookup帮助程序:

lookup帮助程序允许使用 Handlebars 变量进行动态参数解析。它可用于根据输入的数据查找对象的属性。

在您的具体示例中,您可能希望将您的peopleproperties迭代存储在块参数中(例如,命名|person||property|),以及../在您的内部循环中使用,因为上下文已更改。

例如,将所有这些放在一起,HBS 标记可能如下所示:

<table>
    <thead>
        <tr>
            {{#each properties as |property index|}}
                <th><span>{{property}}</span></th>
            {{/each}}
        </tr>
    </thead>
    <tbody>
        {{#each people as |person|}}
            <tr>
                {{#each ../properties as |property|}}
                    <th>{{lookup person property}}</th>
                {{/each}}
            </tr>
        {{/each}}
    </tbody>
</table>

有关生成的 HTML,请参阅此游乐场链接

于 2022-02-03T21:04:51.507 回答