带有嵌套对象数组的Mustache模板

Mustache Template with Nested Array of Objects

本文关键字:Mustache 模板 数组 对象 嵌套      更新时间:2023-09-26

可能需要一些帮助来弄清楚为什么我的Mustache模板没有正确渲染。我很困惑为什么以下不起作用。我相信这是我犯的一个愚蠢的小错误。。。

   var tableRows = [
    {name: 'name1',
     values: ['1','2','3']},
    {name: 'name2',
     values: ['1','2','3']},
    {name: 'name3',
     values: ['1','2','3']}
    ];
var template = $('#mustache-template').html();
$('#target').append(Mustache.render(template, {rows: tableRows}));

HTML模板:

<div id="mustache-template">
    <table>
        <tbody>
              {{#rows}}
                <tr class="">
                  <td>{{name}}</td>
                  {{#values}}
                    <td>{{.}}</td>
                  {{/values}}
                </tr>
              {{/rows}}
        </tbody>
    </table>
</div>

我期望一个表,每个数组项都是自己的行,但我得到的却是:

[object Object]

下面是一个jsFiddle来说明:http://jsfiddle.net/gF9ud/

问题是浏览器将模板处理为无效的表元素。将模板存储在这样的页面上不是一个好主意,请使用<script type="text/template">包装它们:

<script id="mustache-template" type="text/template">
    <table>
      {{#rows}}
        <tr class="">
          <td>{{name}}</td>
          {{#values}}
            <td>{{.}}</td>
          {{/values}}
        </tr>
      {{/rows}}
    </table>
</script>

http://jsfiddle.net/zHkW5/

我发现有效的另一个解决方案是这样注释掉胡子:

<div id="mustache-template">
    <table>
        <tbody>
             <!--  {{#rows}} -->
                <tr class="">
                  <td>{{name}}</td>
                  {{#values}}
                    <td>{{.}}</td>
                  {{/values}}
                </tr>
              <!-- {{/rows}} -->
        </tbody>
    </table>
</div>

对我来说,这完全是我所希望的。我认为浏览器看到tr标签之间的代码有点奇怪。