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

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

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


当前回答

我发现了一个用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"}}

其他回答

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

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

你可以简单地使用如下所示的逻辑运算符:

{{#if (or(eq firstValue 'String_to_compare_value') (eq secondValue 'String_to_compare_value'))}}business logic goes here{{/if}}

{{#if (and(eq firstValue 'String_to_compare_value') (eq secondValue 'String_to_compare_value'))}}business logic goes here{{/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}}

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

模板应该是无逻辑的!

在Ember.js中,你可以在if块helper中使用内联if helper。它可以替换||逻辑运算符,例如:

{{#if (if firstCondition firstCondition secondCondition)}}
  (firstCondition || (or) secondCondition) === true
{{/if}}

这里有一个我使用的块助手的链接:比较块助手。它支持所有标准操作符,并允许您编写如下所示的代码。真的很方便。

{{#compare Database.Tables.Count ">" 5}}
There are more than 5 tables
{{/compare}}