Assume that I have a backbone model that has a bunch of boolean attributes:
Car = Backbone.Model.extend({});
car_one = new Car({
a_c: true,
mp3: true,
gps: false,
touchscreen: false,
// etc...
})
I want to be able to render a list of these boolean attributes, and have an icon beside them, depending on true or false. If true, the icon will be a green tick, otherwise, display a red X icon.
Something in the lines of:
<ul>
<li><img src="tick.png">AC</li>
<li><img src="tick.png">MP3</li>
<li><img src="cross.png">Gps</li>
<li><img src="cross.png">Touch screen</li>
</ul>
Is there a better way to do this, instead of wrapping each li in an if statement in the template:
<% if (model.a_c === true) { %>
// show tick...
<% } else { %>
// show red cross..
<% } %>
I have approximately 12 boolean attributes that need to be rendered like this…
You can access JavaScript functions from within your templates. So you could put something in
window(i.e. the global scope):Then you’ll want to take advantage of the
variableoption to_.template:Then you can have something like this in your template:
and use your template like this:
Demo: http://jsfiddle.net/ambiguous/Yr4m5/
By using the
variableoption you’ll have to say<%= json.attribute %>instead of<%= attribute %>but that’s pretty minor.You could use a similar approach to format the
<li>s one by one and keep more of the HTML in the template.Another option is to throw a
forloop into your template, something like this:Demo: http://jsfiddle.net/ambiguous/983ks/
You’ll notice that this uses the
variable: 'json'option as well, you need that so that you’ll have something to use the[]on to grab a field by name when the name is in a variable.This al