Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
90
rated 0 times [  93] [ 3]  / answers: 1 / hits: 25049  / 13 Years ago, fri, april 1, 2011, 12:00:00

Is it possible to do this with Mustache.js?



var data = {val:3},
template = '<select>' +
'<option value=1>1</option>' +
'<option value=2>2</option>' +
'<option value=3>3</option>' +
'</select>';

var html = Mustache.to_html(template, data);

$(html).appendTo('body');

More From » jquery

 Answers
39

The val attribute doesn't work, because a <select> takes its value from the <option>s which have the selected attribute. I'm not very familar with Mustache, but this should work:



// snip...        
var html = Mustache.to_html(template, data);
$(html)
.find('option[value=3]').attr('selected', true)
.end().appendTo('body');


I think that the template you're using is not idiomatic Mustache — it's too coarse grained; you're not actually templating anything. Something like this might be more Mustache-y:



var template = '<select>{{#options}}' +
'<option value={{val}} {{#sel}}selected{{/sel}}>' +
'{{txt}}' +
'</option>' +
'{{/options}}</select>',

data = {options: [
{val: 1, txt: 'uno'},
{val: 2, txt: 'dos'},
{val: 3, txt: 'tres', sel: true}
]};

var html = Mustache.to_html(template, data);

$(html).appendTo('body');


Demo →


[#92956] Thursday, March 31, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaidyn

Total Points: 633
Total Questions: 102
Total Answers: 100

Location: Trinidad and Tobago
Member since Thu, Dec 1, 2022
2 Years ago
;