With a Handlebars.js template like this...
<select> <option value="Completed">Completed</option> <option value="OverDue">OverDue</option> <option value="SentToPayer">SentToPayer</option> <option value="None">None</option> </select>
... and data like this...
{ "id" : 1, "name" : "World" "status" : "OverDue", "date" : "2012-12-21" }
I want to render HTML like this.
<select> <option value="Completed">Completed</option> <option value="OverDue" selected="selected">OverDue</option> <option value="SentToPayer">SentToPayer</option> <option value="None">None</option> </select>
Which way is the easiest?
To get the value of a select or dropdown in HTML using pure JavaScript, first we get the select tag, in this case by id, and then we get the selected value through the selectedIndex property. The value "en" will be printed on the console (Ctrl + Shift + J to open the console).
Precompiling Templates Inside NodeJS If you wish to precompile templates from inside NodeJS--without invoking "handlebars" from the command line--that can be done with Handlebars. precompile. Transmit the string result of this function to your clients, and they can in turn parse that with Handlebars. template.
Handlebars is a simple templating language. It uses a template and an input object to generate HTML or other text formats. Handlebars templates look like regular text with embedded Handlebars expressions. A handlebars expression is a {{ , some contents, followed by a }} .
Templates The recommended way of adding templates to your page is by including them in <script> tags with a special type. The type attribute is important, otherwise the browser will attempt to parse them as JavaScript (which they are not). The templates have an easy to grasp syntax.
I found a lot of over complicated solutions and decided to write my own using a Handlebars helper.
With this partial (using Jquery) ...
window.Handlebars.registerHelper('select', function( value, options ){ var $el = $('<select />').html( options.fn(this) ); $el.find('[value="' + value + '"]').attr({'selected':'selected'}); return $el.html(); });
You can wrap selects in your Handlebars template with {{#select status}}...
<select> {{#select status}} <option value="Completed">Completed</option> <option value="OverDue">OverDue</option> <option value="SentToPayer">SentToPayer</option> <option value="None">None</option> {{/select}} </select>
and end up with this...
<select> <option value="Completed">Completed</option> <option value="OverDue" selected="selected">OverDue</option> <option value="SentToPayer">SentToPayer</option> <option value="None">None</option> </select>
Presto!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With