【发布时间】:2015-04-10 04:48:27
【问题描述】:
我有以下代码:
<div class="form-group {{#if afFieldIsInvalid name='latitude' OR name='longitude'}}has-error{{/if}}">......</div>
如何在空格键模板的 if 条件中使用 AND/OR?
【问题讨论】:
我有以下代码:
<div class="form-group {{#if afFieldIsInvalid name='latitude' OR name='longitude'}}has-error{{/if}}">......</div>
如何在空格键模板的 if 条件中使用 AND/OR?
【问题讨论】:
你可以使用 if-else 语法来做到这一点
<div class="form-group {{#if afFieldIsInvalid}} latitude {{else}} longitude {{/if}} has-error">...</div>
【讨论】:
使解决方案更进一步。这会添加比较运算符。
Handlebars.registerHelper('ifCond', function (v1, operator, v2, options) {
switch (operator) {
case '==':
return (v1 == v2) ? options.fn(this) : options.inverse(this);
case '===':
return (v1 === v2) ? options.fn(this) : options.inverse(this);
case '!=':
return (v1 != v2) ? options.fn(this) : options.inverse(this);
case '!==':
return (v1 !== v2) ? options.fn(this) : options.inverse(this);
case '<':
return (v1 < v2) ? options.fn(this) : options.inverse(this);
case '<=':
return (v1 <= v2) ? options.fn(this) : options.inverse(this);
case '>':
return (v1 > v2) ? options.fn(this) : options.inverse(this);
case '>=':
return (v1 >= v2) ? options.fn(this) : options.inverse(this);
case '&&':
return (v1 && v2) ? options.fn(this) : options.inverse(this);
case '||':
return (v1 || v2) ? options.fn(this) : options.inverse(this);
default:
return options.inverse(this);
}
});
在这样的模板中使用它:
{{#ifCond name='latitude' '||' name='longitude'}}
【讨论】:
您有一个专为这种情况设计的扩展程序。
您可以使用类似这样的“与”条件:
{{#if $in yourVariable 'case1' 'case2' }}
Your code Here
{{/if}}
【讨论】:
尝试使用“||”而不是使用“OR”。 或者在 javascript 文件中定义一个方法。
【讨论】:
空格键无法处理逻辑表达式,因此您需要创建一个助手来为您处理计算。
实际上,您可以使用这样的嵌套 if 来实现 and 功能:
{{#if condition1}}
{{#if condition2}}
<p>Both condition hold!</p>
{{/if}}
{{/if}}
像这样or:
{{#if condition1}}
<p>One of the conditions are true!</p>
{{else}}
{{#if condition2}}
<p>One of the conditions are true!</p>
{{/if}}
{{/if}}
但我更喜欢使用助手。
【讨论】:
Spacebars 是 Handlebars 的扩展,旨在成为一种无逻辑模板语言。
解决方案是注册一个助手。对于一般情况,请参阅以下类似问题:
要在 Meteor 中定义助手,请使用 Template.registerHelper
【讨论】: