Can mustache iterate a top-level array?

greim picture greim · Jun 29, 2011 · Viewed 65.8k times · Source

My object looks like this:

['foo','bar','baz']

And I want to use a mustache template to produce from it something like this:

"<ul><li>foo</li><li>bar</li><li>baz</li></ul>"

But how? Do I really have to munge it into something like this first?

{list:['foo','bar','baz']}

Answer

Dan Jordan picture Dan Jordan · Apr 4, 2012

You can do it like this...

Mustache.render('<ul>{{#.}}<li>{{.}}</li>{{/.}}</ul>', ['foo','bar','baz']);

It also works for things like this...

var obj = [{name: 'foo'}, {name: 'bar'}];
var tmp = '<ul>{{#.}}<li>{{name}}</li>{{/.}}</ul>';
Mustache.render(tmp, obj);