快速的問題。是否有可能在handlebars條件中評估布爾屬性以外的其他內容?Handlebars條件 - 僅限布爾屬性?
如這工作
//elsewhere... myproperty = true
{{#if myproperty}}...
任何方式與其他條件句可以做什麼?例如
//elsewhere... myproperty = 3
{{#if myproperty<4}}...
快速的問題。是否有可能在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語句。
最好的解決辦法是使用ember-truth-helpers
所以你的情況,你會用{{if (lt myproperty 4)}}
沒有試過尚未但它看上去很聰明,直接。請問爲什麼Handlebars本身不支持更復雜的條件... – rjoxford 2015-02-08 12:02:15
我更新了我的答案,以迴應您的評論:) – Eclecticist 2015-02-08 21:34:29
右感謝,是的,這使得很多道理。總是要考慮更多! – rjoxford 2015-02-09 11:28:49