[英]Is there a ternary operator in handlebars.js?
在 Handlebars 中,是否有三元运算符? 我不是说if else
; 我的意思是像a == true ? "a" : "b"
a == true ? "a" : "b"
。
if
助手可以通过向它传递三个参数来用作三元运算符。
在以下示例中,按钮的默认值为"Save Changes"
,但当model.isSaving
为 true 时,该值会暂时更改为Saving...
。
<button>{{if model.isSaving "Saving..." "Save Changes"}}</button>
...或者,在另一个助手中使用:
{{input type="submit" value=(if model.isSaving "Saving..." "Save Changes")}}
如果你真的想的话,你可以在handlbars中建立你自己的助手。 像ternary(a==true, "a", "b")
类的东西。 有关这方面的更多信息,请参阅文档。 m90 的想法不是车把背后的想法。 这个想法是在你的模板中没有明确的代码,只调用助手和对象。
这对我有用
{{#if final}} "Final" {{^}} "Interim" {{/if}}
下面的代码可用于三元或任何类型的表达式 eval。
警告:请在可以安全使用 eval 的场景中使用此代码。
{{#if (myfunc "(a[0] + 1) % 2 === 0" arg1)}}
{{/if}}
{{#if (myfunc "(a[0] + a[1]) % 2 === 0" arg1 arg2)}}
{{/if}}
车把辅助功能
myfunc: (exp, ...a) => {
return eval(exp);
}
我有一个帮手(注意里面也可以使用其他帮手) https://gist.github.com/terion-name/d87ed8907f1bb2e25f32
// app/helpers/iftrue.js
import Ember from 'ember';
export function iftrue(params) {
if (params[0]) {
return params.length === 2 ? params[0] : params[1];
}
if (params.length === 2) {
return params[1];
} else if (params.length === 3) {
return params[2];
}
return null;
}
export default Ember.Helper.helper(iftrue);
有两个参数:如果第一个参数的计算结果为 true,它将被打印,否则第二个
{{iftrue project.price 'N/A'}} // $9.99
{{iftrue project.priceNotAvailable 'N/A'}} // N/A
使用三个参数:如果第一个参数计算结果为真,则打印第二个,否则打印第三个
// If deadline is set formatted date will be printed, otherwise 'N/A'
{{iftrue project.deadline (moment-format project.deadline 'DD.MM.YYYY') 'N/A'}}
我猜内置的if
助手曾经支持用作三元运算符,但现在不再这样做了。 我按如下方式覆盖它,因此它可以用作块助手或三元运算符。
if(...args: any[]) {
const options = args.pop();
const {fn} = options;
if(args.length < (fn ? 1 : 2)) {
throw new Handlebars.Exception(
fn ?
'#if requires exactly one argument' :
'if requires two or three arguments'
);
}
let conditional = args.shift();
if(typeof conditional === 'function')
conditional = conditional.call(this);
// Default behavior is to render the positive path if the value is truthy and not empty.
// The `includeZero` option may be set to treat the condtional as purely not empty based on the
// behavior of isEmpty. Effectively this determines if 0 is handled by the positive path or negative.
if ((!options.hash.includeZero && !conditional) || Utils.isEmpty(conditional)) {
if(fn)
return options.inverse(this);
let [, b] = args;
return typeof b === 'function' ? b.call(this) : b;
}
if(fn) return fn(this);
const [a] = args;
return typeof a === 'function' ? a.call(this) : a;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.