Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add options to dropdown using Mustache template?

Here is my javascript object and i want to add options to dropdown? I want property name goes as value and property value go as text in each option?

{ "": "", "CSharp40": "C# 4.0", ".NET": ".NET", "JQuery": "JQuery", "Javascript": "Javascript" }

The output would be like below

<select id="courses"> 
    <option value=""></option>
    <option value="CSharp40">C# 4.0</option>
    <option value=".NET">.NET</option>
    <option value="JQuery">JQuery</option>
    <option value="Javascript">Javascript</option>
</select>

can you tell me how to write Mustache template for this? Thanks in advance

like image 807
user845392 Avatar asked Jan 25 '12 16:01

user845392


1 Answers

Agreed that since your data is a list, it should be in an array. But instead of manually iterating over your array, I'd propose that you use this Mustache-ier technique. Tested.

var courses = [
    {val: "", title:""},
    {val: "CSharp40", title: "C# 4.0"},
    {val: ".NET", title: ".NET"},
    {val: "JQuery", title: "JQuery"},
    {val: "Javascript", title: "Javascript"}
];

var template = "<select id='courses'>{{#list}}<option value='{{val}}'>{{title}}</option>{{/list}}</select>";

// because Mustache doesn't like anonymous arrays of objects
var rendered_template = Mustache.to_html(template, {"list":courses} );

$('#list-container').html(rendered_template);
like image 117
r.l.parker Avatar answered Sep 28 '22 06:09

r.l.parker