Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Mustache.js if the object is in a array?

i use Mustache.js succusefully display the html ,here's the code

        var mygame = {
        player:'viking',
        games:[{name:'d1',type:'avg'},{name:'cod7',type:'fps'},{name:'war3',type:'rts'}]
        };
    var template = '{{player}}  is a good guy<br/> <ul>{{#games}}<li>name:{{name}} and type:{{type}} </li>{{/games}}</ul>';
    var html = Mustache.to_html(template, mygame);
    var con = document.getElementById('container');
    con.innerHTML = html;

but how do i use it when the object is a array ,like

var mygames = [{name:'d1',type:'avg'},{name:'cod7',type:'fps'},{name:'war3',type:'rts'}];
like image 259
vikingmute Avatar asked Jun 09 '11 11:06

vikingmute


3 Answers

You can do it like this:

var model = [{name:'d1',type:'avg'},{name:'cod7',type:'fps'},{name:'war3',type:'rts'}];
var template = '<ul> {{#.}} <li>name:{{name}} and type:{{type}} </li> {{/.}} </ul>';
var html = Mustache.to_html(template, model);
like image 104
grigson Avatar answered Oct 16 '22 09:10

grigson


Try this:

var mygames = [{name:'d1',type:'avg'},{name:'cod7',type:'fps'},{name:'war3',type:'rts'}];

var mygame = {
    player: 'viking',
    games: mygames
}
var template = '{{player}} is a good guy<br /> <ul>{{#games}}<li>name:{{name}} and type:{{type}} </li>{{/games}}</ul>';
var html = Mustache.to_html(template, mygame);
var con = document.getElementById('container');
con.innerHTML = html;
like image 41
Nathan DeWitt Avatar answered Oct 16 '22 07:10

Nathan DeWitt


you need to do something like this:

var mygames = {games: [{name:'d1',type:'avg'},{name:'cod7',type:'fps'},{name:'war3',type:'rts'}]};

var template= "{{#games}} Player name: {{name}} Type: {{type}}{{/games}}";

var html = Mustache.to_html(template, mygames);
var con = document.getElementById('container');
con.innerHTML = html;

or simply loop over mygames object and append the html

var html="";
var template= "Player name: {{name}} Type: {{type}};"
for (var i=0;i<mygames.length;i++)
{
   html+=Mustache.to_html(template, mygames[i]);
}
var con = document.getElementById('container');
con.innerHTML = html;

Hope this helps

like image 2
Baz1nga Avatar answered Oct 16 '22 09:10

Baz1nga