在handlebars JS中是否有一种方法可以将逻辑操作符合并到标准handlebars. JS条件操作符中?就像这样:

{{#if section1 || section2}}
.. content
{{/if}}

我知道我可以编写自己的助手,但首先我想确保我没有重复工作。


当前回答

如果您只是想检查一个元素或另一个元素是否存在,您可以使用这个自定义帮助器

Handlebars.registerHelper('if_or', function(elem1, elem2, options) {
  if (Handlebars.Utils.isEmpty(elem1) && Handlebars.Utils.isEmpty(elem2)) {
    return options.inverse(this);
  } else {
    return options.fn(this);
  }
});

像这样

{{#if_or elem1 elem2}}
  {{elem1}} or {{elem2}} are present
{{else}}
  not present
{{/if_or}}

如果你还需要能够有一个“或”来比较 函数返回值 我宁愿添加另一个返回所需结果的属性。

模板应该是无逻辑的!

其他回答

改进的解决方案,基本上适用于任何二进制操作符(至少数字,字符串不适用于eval,如果使用用户输入的非定义操作符,请注意可能的脚本注入):

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);

        case ">":
            return (v1>v2)?options.fn(this):options.inverse(this);

        case ">=":
         return (v1>=v2)?options.fn(this):options.inverse(this);

        default:
            return eval(""+v1+operator+v2)?options.fn(this):options.inverse(this);
    }
});

对于那些有比较对象属性的问题,在帮助器中添加这个解决方案

Ember.js helper无法正确识别参数

我发现了一个用CoffeeScript制作的npm包,它有很多令人难以置信的有用的把手助手。在下面的URL中查看文档:

https://npmjs.org/package/handlebars-helpers

您可以执行wget http://registry.npmjs.org/handlebars-helpers/-/handlebars-helpers-0.2.6.tgz来下载它们并查看包的内容。

您将能够执行如下操作:{{#is number 5}}或{{formatDate date "%m/%d/%Y"}}

不幸的是,这些解决方案都不能解决“或”操作符“cond1 || cond2”的问题。

检查第一个值是否为真 使用"^"(或)并检查cond2是否为真 {{#如果cond1}} 行动起来 {{^}} {{#如果cond2}} 行动起来 {{/如果}} {{/如果}}

这违反了DRY规则。为什么不用偏微分函数来简化呢

{{#if cond1}}
    {{> subTemplate}}
{{^}}
    {{#if cond2}}
        {{> subTemplate}}
    {{/if}}
{{/if}}

通过运行以下命令安装烬真相助手插件

Ember安装Ember -truth-helpers

您可以开始使用大多数逻辑运算符(eq,not-eq,not,and,or,gt,gte,lt,lte,xor)。

{{#if (or section1 section2)}}  
...content  
{{/if}}

你甚至可以包含子表达式来更进一步,

{{#if (or (eq section1 "section1") (eq section2 "section2") ) }}  
...content  
{{/if}}