javascript - Handlebars 模板中的 bool 逻辑

标签 javascript ember.js handlebars.js

是否可以在 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/

相关文章:

javascript - 在 Angular 中解析来自 API 的 JSON 响应

javascript - 在 Ember 数据中加载关系模型

ruby - 单页应用程序中的elasticsearch

node.js - Express 中的 app.set 和 app.engine

javascript - Foundation Orbit 无法与 Handlebars 配合使用

javascript - 在 Vue.js 3 中搜索 react 数组

javascript - 尝试使用 Indeed API 根据输入字段检索职位时出错

javascript - 计算具有相同类别的每个元素的 margin

ember.js - 使用标签扩展 TextField

javascript - 获取 Ember 中所有可用的模板