简体   繁体   中英

Mustache template with different states

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.

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}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM