My backbone model has a boolean value (isRegistered). When I render out the view I want to have a checkbox checked or unchecked depending on the true/false value of the boolean.
My current effort looks like this:
<input id="isRegisteredCheckbox" checked="<%= isRegistered ? 'checked': ''"/>
this doesn't work because according to the W3C Specification the checked attribute needs to be completely removed to uncheck a checkbox.
How do I do it using backbone template?
You could use a test to enclose checked='checked'
<input id="isRegisteredCheckbox" <% if (isRegistered) { %>checked="checked"<% } %> />
You don't need the checked=
part. just print out checked in the tag if it needs to be checked.
Now that we've determined that just printing "checked" out is valid html, you might try for simplicity:
render:
var registered;
var tmpl = _.template(your template);
isRegistered ? registered = 'checked' : registered = '';
var tmpl_data = _.extend(this.model.toJSON(), {registered: registered}); // or whatever values you need to add
$(this.el).html(tmpl(tmpl_data));
template:
<input type="checkbox" {{ registered }}>
No need for messy conditionals in your template using this method.
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