Reputation: 2263
I have a status flag on my model which can take one of four values: active, inactive, processing or uploading.
In a mustache template I want to switch on and off different parts of the template depending on which value the status flag is. Is there a decent way to do this?
I don't really want to have 4 different templates-one for each state.
I tried using an isActive, isProcessing etc method on the model which returns this.get('status') === 'active'
, but as its a function it won't be passed into the template.
Upvotes: 1
Views: 485
Reputation: 434665
AFAIK, the usual approach is convert your model to a simple blob of data with toJSON
and then hand the blob of data to your Mustache template. So, all you need to do is provide your own toJSON
that includes your method calls as attributes. For example:
toJSON: function() {
var json = Backbone.Model.prototype.toJSON.call(this);
json.isActive = this.isActive();
json.isProcessing = this.isProcessing();
return json;
}
Demo (open your console please): http://jsfiddle.net/ambiguous/22aYH/
Then, you can have things like this in your template:
{{#isActive}}It is active!{{/isActive}}
{{#isProcessing}}Be patient, we're working on it...{{/isProcessing}}
Upvotes: 4