简体   繁体   English

小胡子模板与不同的状态

[英]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. 我真的不想拥有4个不同的模板 - 每个州一个。

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. 我尝试在模型上使用isActive,isProcessing等方法返回this.get('status') === 'active' ,但作为一个函数,它不会传递给模板。

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. AFAIK,通常的方法是使用toJSON将模型转换为简单的数据blob,然后将数据blob toJSON给Mustache模板。 So, all you need to do is provide your own toJSON that includes your method calls as attributes. 因此,您需要做的就是提供您自己的toJSON ,其中包含您的方法调用作为属性。 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/ 演示(请打开你的控制台): 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}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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