Mustache template with nested array of objects

It might be a little help figuring out why my Mustache template is not displaying properly. I am very confused why the following does not work. I'm sure this is my stupid mistake 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 expect the table with each element of the array to be its own row, but instead I get the following:

[object Object]

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

+6
source share
2 answers

The problem is that the browser treats your template as an invalid table element. It is not recommended to store your templates on such a page, use <script type="text/template"> to transfer 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/

+13
source

Another solution I found is to compile a mustache like this:

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

For me it looked like I was hoping. I think a browser like freaks sees code between tr tags.

+3
source

All Articles