Handlebars条件 - 仅限布尔属性?
问题描述:
快速的问题。是否有可能在handlebars条件中评估布尔属性以外的其他内容?Handlebars条件 - 仅限布尔属性?
如这工作
//elsewhere... myproperty = true
{{#if myproperty}}...
任何方式与其他条件句可以做什么?例如
//elsewhere... myproperty = 3
{{#if myproperty<4}}...
答
您不能在模板做{{#if myproperty<4}}
。
请参见以下问题为在这样的情况下
How do I make a conditional helper with ember-cli and handlebars 2.0.0?
答
做什么没有一个帮手的例子,你不能有if
的评估条件。你可以,但是,做一个帮手做到这一点:
Handlebars.registerHelper('iff', function(left, condi, right, options) {
function ret(bool) {
if (bool) {
return options.fn(this);
} else {
return options.inverse(this);
}
}
switch (condi) {
case "==":
ret(left == right);
case "!=":
ret(left != right);
case ">":
//etc, etc, you get the idea
default:
return options.inverse(this);
}
});
用法:
{{#iff myproperty "<" 4}}
Myproperty is less than 4
{{else}}
Myproperty is greater than or equal to 4
{{/iff}}
- 编辑 -
没有尝试这样做还,但它看起来明智和直截了当。回避 的问题,为什么把手不支持更复杂的条件语句 本身......
这是很好的做法,你的逻辑从模板(视图)分开,因为它使你的代码更易于维护。本质上,它遵循separation of concerns原则。
就个人而言,我认为有条件的if
也会有用,因为在模板中一定要有一个if
语句的地方,同时保持逻辑和视图不同。但是,由于默认情况下不包含它,它可以让用户从一定程度上节省自己,所以你最终不会看到20+嵌套的if语句。
没有试过尚未但它看上去很聪明,直接。请问为什么Handlebars本身不支持更复杂的条件... – rjoxford 2015-02-08 12:02:15
我更新了我的答案,以回应您的评论:) – Eclecticist 2015-02-08 21:34:29
右感谢,是的,这使得很多道理。总是要考虑更多! – rjoxford 2015-02-09 11:28:49