6

可以使用一点帮助来找出我的 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/

4

2 回答 2

13

问题是浏览器将您的模板作为无效的表格元素处理。将模板存储在这样的页面上并不是一个好主意,<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/

于 2013-02-09T21:09:07.830 回答
3

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

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

对我来说,它完全按照我的希望呈现。我认为浏览器会在标签之间看到代码tr

于 2013-05-27T21:03:55.997 回答