Handlebars JS Example 1

by Durtto

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.3.0/handlebars.js"></script>
<h1>Handlebars JS Example</h1>
<script id="some-template" type="text/x-handlebars-template"> 

    <select dropdown multiple class="dropdown" name="color">
        {{#each colors}}
            <option value="{{value}}" {{isSelected parentColor id}}>{{title}}</option>
        {{/each}}
</select>
</script>

CSS

body {
    font:15px arial, sans-serif;
}
h1 {
    margin: 0 0 10px 0;
    padding: 5px;
    font-size: 24px;
    background-color: #999;
    color: #fff;
}
table {
    margin: 10px;
}
th, td {
    padding: 5px;
    border: 1px solid #999;
}
th {
    background: #ccc;
}
tr:nth-child(odd) {
    background: #eee;
}
td a {
    color: #000;
    text-decoration: underline;
}

JavaScript

var source = $("#some-template").html();
var template = Handlebars.compile(source);

var data = {
    colors: [
        {id:1,value:1,title:"red",parentColor:2},
        {id:2,value:2,title:"green",parentColor:2},
        {id:3,value:3,title:"blue",parentColor:1}
    ]
};


Handlebars.registerHelper('isSelected', function (input, color) {
    return input === color ? 'selected' : '';
});

$('body').append(template(data));