是否可以在 handlebars 条件中执行 bool 逻辑?
现在我用 Controller 函数来欺骗这种行为,所以我最终得到了 Controller
App.ApplicationController = Ember.Controller.extend({
bool1: true,
bool2: true,
both: function(){ return this.bool1 && this.bool2; }.property('content.both'),
});
这允许我使用的 Handlebars 模板
<script type="text/x-handlebars">
{{#if both}}
<p> both were true </p>
{{/if}}
</script>
这工作正常,但会引发一些问题。首先,它掩盖了正在发生的事情(特别是如果没有使用好的函数名)。其次,它似乎有点违反了 MVC 分离。
是否有可能按照
<script type="text/x-handlebars">
{{#if bool1 && bool2}} <!-- this will not actually work -->
<p> both were true </p>
{{/if}}
</script>
让它工作了吗?
最佳答案
也许你可以试试这个 Handlebars 助手:
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);
default:
return options.inverse(this);
}
});
并像这样调用它:
{{#ifCond showDistance "&&" distance}}
<span class="distance">
{{distance}}
</span>
{{else}}
{{#if showRegion}}
<span class="region">
</span>
{{/if}}
{{/ifCond}}
关于javascript - Handlebars 模板中的 bool 逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14839375/