把手js,获取特定的对象数组并循环通过

时间:2016-03-11 14:26:38

标签: json if-statement handlebars.js

我试图从阵列中生成两个表。

"tables": [
{
"tableName": "table1",
"dataRow": ["name": "test858"]
},
{
"tableName": "table2",
"anotherRow": ["name": "test123"]
}
]

我试过这个

{{#each tables}}
            <table>
                <thead>
                    <tr>
                        <th>{{tableName}}</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        {{#if dataRow}}
                        <td>test1</td>
                        {{else}}
                        <td>test2</td>
                        {{/if}}
                    </tr>
                </tbody>
            </table>
 {{/each}} 

这将打印两个表名和&#34; test2&#34;

如何在两个数组中循环?

1 个答案:

答案 0 :(得分:0)

工作示例JSFiddle

var entry_template = document.getElementById('entry-template').innerHTML;
var tables = [
{
"tableName": "table1",
"dataRow": [{"name": "test858"}]
},
{
"tableName": "table2",
"anotherRow": [{"name": "test123"}]
}
];

var template = Handlebars.compile(entry_template);
var template_with_data = template(tables);

document.getElementById('data').insertAdjacentHTML('afterbegin', template_with_data);

模板:

<script id="entry-template" type="text/x-handlebars-template">
{{#each this}}
            <table>
                <thead>
                    <tr>
                        <th>{{tableName}}</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        {{#if dataRow}}
                        <td>test1</td>
                        {{else}}
                        <td>test2</td>
                        {{/if}}
                    </tr>
                </tbody>
            </table>
 {{/each}}  
</script>
<div id="data">
</div>