Using handlebars to setup a select box in CSUI

Look at the standard problem:

Your handlebars template contains a Selectbox to display a the status of a task:

<select name="status" id="Status" class="binf-selectpicker" data-style="binf-btn-warning">

<select name="status" id="Status" class="binf-selectpicker" data-style="binf-btn-warning">

{{#select status}}

<option value="0" selected="">Pending</option> 

<option value="1">In Process</option> <option value="2">Issue</option>

<option value="3">On Hold</option> 

<option value="-1">Completed</option> 

<option value="-2">Cancelled </option>

{{/select}} 

</select>

And the values you receive from the REST Calls are between -2 and 3.

How can you transfer this in a “selected” clause in the html select box?

 

Easy.

Ass a select helper in your main marionette view:

 Handlebars.registerHelper('select', 
function (selected, options) { 
Handlebars.registerHelper('select', function (selected, options) 
{ return options.fn(this).replace( new RegExp(' value=\"' + selected + '\"'),
 '$& selected="selected"'); });

This handlebars helper named “select” will examine the coding tagged betweern a {{select}} and a {{/select}} in your handlebars template and insert at the option clause which is selected a ‘selected=”” ‘ clause. Then the Selectbox is ready to use.

 

Simply add a

status: this.model.get('status'),

to be returned in your template helper and the

{{#select status}}

...

{{/select}}

 

will trigger your select box helper to check for the v ariable status and to add a selected at the proper place.

Thats the magic behind the handlebars select helpers.