[英]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.