Mustache Template with Nested Array of Objects

自作多情 提交于 2019-12-21 02:34:10

问题


Could use a little help figuring out why my Mustache template isn't rendering properly. I'm very confused why the following isn't working. I'm sure it's a minor stupid mistake of mine or something...

   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 Template:

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

I'm expecting a table with each array item being its own row, but instead I'm getting this:

[object Object]

Here's a jsFiddle to illustrate: http://jsfiddle.net/gF9ud/


回答1:


The problem is that the browser handles your template as an invalid table element. It's not a good idea to store your templates on a page like that, use <script type="text/template"> to wrap them:

<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/




回答2:


Another solution that I found works is to comment out the mustache like so:

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

For me, it rendered exactly as I had hoped. I think the browser kind of freaks seeing code between tr tags.



来源:https://stackoverflow.com/questions/14791312/mustache-template-with-nested-array-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!