Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone underscore Checkbox passing value issue

I have a very basic issue, but cannot see a solution to it. Maybe I need to change my way of thinking. Basically I am getting a model back in the JSON file, but I can't figure out how to convert true to checked. For example I know the {{-done}} is either true or false.

input type="checkbox"  id="chkName"   <%= {{-done}} ? "checked" : "" %>

I see loads of examples like this, but does not work for me. Is it because of the way I have brought back the true/false value.

Any help would be appreciated

like image 597
Mark O Keeffe Avatar asked Oct 22 '12 21:10

Mark O Keeffe


1 Answers

Your problem is that you are using the wrong type of Underscore.js template tag, the tag you are using is for interpolating a value and having it HTML-escaped.

To explain, there are three types of tags within underscore templates,

  1. <%= %> - Interpolate - Evaluates the data of the property and prints it.
  2. <%- %> Escape Evaluates the data and prints it HTML-escaped.
  3. <% %> Evaluate Allows you to execute JavaScript in your template.

In addition when executing JavaScript within your template you can use the Print method to print out some text (for example the results of an attribute).

Based on the above in your case you need to run a conditional within your template to print out checked if done evaluates to true. What you can therefore do is something like the following

<% if(done) { %> 'checked="checked" <% } %>

Or you can use the print method

<% print(done ? 'checked="checked"' : '') %>

Edit:

Based on the template you posted, the following template should work

     <script id="item-template"  type="text/template">   
         <input type="checkbox" id="toggle" <% print( done ?  'checked="checked"' : '') %> /> 
           <span class="text">{{-done}}</span>
           <a id="dele" data-role="button" data-inline="true" data-icon='delete' >Delete</a>
        </script>

Here is a link to a jsBin using the default ERB-style delimiters

And here's a second one using mustache style delimiters.

like image 75
Jack Avatar answered Oct 08 '22 19:10

Jack