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

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

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


当前回答

为了那些生活在边缘的人,把这个提升一个档次。

要点:https://gist.github.com/akhoury/9118682 演示:下面是代码片段

句柄Helper: {{#xif表达式}}{{else}} {{/xif}}

一个helper来执行带有任意表达式的IF语句

EXPRESSION是一个正确转义的字符串 是的,你需要正确转义字符串字面量或只是交替单引号和双引号 您可以访问任何全局函数或属性,即encodeURIComponent(property) 这个例子假设你将这个上下文传递给你的handlebars模板({name: 'Sam', age: '20'}),注意年龄是一个字符串,只是为了我可以在后面的文章中演示parseInt()

用法:

<p>
 {{#xif " name == 'Sam' && age === '12' " }}
   BOOM
 {{else}}
   BAMM
 {{/xif}}
</p>

输出

<p>
  BOOM
</p>

JavaScript:(这取决于另一个助手-继续阅读)

 Handlebars.registerHelper("xif", function (expression, options) {
    return Handlebars.helpers["x"].apply(this, [expression, options]) ? options.fn(this) : options.inverse(this);
  });

帮助句柄:{{x表达式}}

一个执行javascript表达式的助手

EXPRESSION是一个正确转义的字符串 是的,你需要正确转义字符串字面量或只是交替单引号和双引号 你可以访问任何全局函数或属性,即parseInt(property) 这个例子假设你将这个上下文传递给了你的handlebars模板({name: 'Sam', age: '20'}),年龄是一个用于演示的字符串,它可以是任何东西。

用法:

<p>Url: {{x "'hi' + name + ', ' + window.location.href + ' <---- this is your href,' + ' your Age is:' + parseInt(this.age, 10)"}}</p>

输出:

<p>Url: hi Sam, http://example.com <---- this is your href, your Age is: 20</p>

JavaScript:

这看起来有点大,因为为了清晰起见,我扩展了语法并注释了几乎每一行

Handlebars.registerHelper("x", function(expression, options) { var result; // you can change the context, or merge it with options.data, options.hash var context = this; // yup, i use 'with' here to expose the context's properties as block variables // you don't need to do {{x 'this.age + 2'}} // but you can also do {{x 'age + 2'}} // HOWEVER including an UNINITIALIZED var in a expression will return undefined as the result. with(context) { result = (function() { try { return eval(expression); } catch (e) { console.warn('•Expression: {{x \'' + expression + '\'}}\n•JS-Error: ', e, '\n•Context: ', context); } }).call(context); // to make eval's lexical this=context } return result; }); Handlebars.registerHelper("xif", function(expression, options) { return Handlebars.helpers["x"].apply(this, [expression, options]) ? options.fn(this) : options.inverse(this); }); var data = [{ firstName: 'Joan', age: '21', email: 'joan@aaa.bbb' }, { firstName: 'Sam', age: '18', email: 'sam@aaa.bbb' }, { firstName: 'Perter', lastName: 'Smith', age: '25', email: 'joseph@aaa.bbb' }]; var source = $("#template").html(); var template = Handlebars.compile(source); $("#main").html(template(data)); h1 { font-size: large; } .content { padding: 10px; } .person { padding: 5px; margin: 5px; border: 1px solid grey; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0/handlebars.min.js"></script> <script id="template" type="text/x-handlebars-template"> <div class="content"> {{#each this}} <div class="person"> <h1>{{x "'Hi ' + firstName"}}, {{x 'lastName'}}</h1> <div>{{x '"you were born in " + ((new Date()).getFullYear() - parseInt(this.age, 10)) '}}</div> {{#xif 'parseInt(age) >= 21'}} login here: <a href="http://foo.bar?email={{x 'encodeURIComponent(email)'}}"> http://foo.bar?email={{x 'encodeURIComponent(email)'}} </a> {{else}} Please go back when you grow up. {{/xif}} </div> {{/each}} </div> </script> <div id="main"></div>

Moar

如果你想访问上层作用域,这个略有不同,表达式是所有参数的JOIN, 用法:说上下文数据是这样的:

// data
{name: 'Sam', age: '20', address: { city: 'yomomaz' } }

// in template
// notice how the expression wrap all the string with quotes, and even the variables
// as they will become strings by the time they hit the helper
// play with it, you will immediately see the errored expressions and figure it out

{{#with address}}
    {{z '"hi " + "' ../this.name '" + " you live with " + "' city '"' }}
{{/with}}

Javascript:

Handlebars.registerHelper("z", function () {
    var options = arguments[arguments.length - 1]
    delete arguments[arguments.length - 1];
    return Handlebars.helpers["x"].apply(this, [Array.prototype.slice.call(arguments, 0).join(''), options]);
});

Handlebars.registerHelper("zif", function () {
    var options = arguments[arguments.length - 1]
    delete arguments[arguments.length - 1];
    return Handlebars.helpers["x"].apply(this, [Array.prototype.slice.call(arguments, 0).join(''), options]) ? options.fn(this) : options.inverse(this);
});

其他回答

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

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

你不能把你的表达式写在句柄模板中,但你所有的逻辑(表达式)都写在express.js中

app.js

res.render("view.hbs", {expression: section1 || section2})

view.hbs

{{#if expression}}
  <h1> My Expression Returned True </h1>
{{ else }}
  <h2>My Expression Returned False</h2>
{{/if}} <!-- End IF -->

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

{{#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}}

在关闭之前,如果你能写出你的业务逻辑

对于三元helper,还有另一个不正确的解决方案:

'?:' ( condition, first, second ) {
  return condition ? first : second;
}

<span>{{?: fooExists 'found it' 'nope, sorry'}}</span>

或者一个简单的合并helper:

'??' ( first, second ) {
  return first ? first : second;
}

<span>{{?? foo bar}}</span>

由于这些字符在句柄标记中没有特殊含义,因此可以自由地将它们用于帮助器名称。

如果你想检查多个条件,这里有一个解决方案:

/* Handler to check multiple conditions
   */
  Handlebars.registerHelper('checkIf', function (v1,o1,v2,mainOperator,v3,o2,v4,options) {
      var operators = {
           '==': function(a, b){ return a==b},
           '===': function(a, b){ return a===b},
           '!=': function(a, b){ return a!=b},
           '!==': function(a, b){ return a!==b},
           '<': function(a, b){ return a<b},
           '<=': function(a, b){ return a<=b},
           '>': function(a, b){ return a>b},
           '>=': function(a, b){ return a>=b},
           '&&': function(a, b){ return a&&b},
           '||': function(a, b){ return a||b},
        }
      var a1 = operators[o1](v1,v2);
      var a2 = operators[o2](v3,v4);
      var isTrue = operators[mainOperator](a1, a2);
      return isTrue ? options.fn(this) : options.inverse(this);
  });

用法:

/* if(list.length>0 && public){}*/

{{#checkIf list.length '>' 0 '&&' public '==' true}} <p>condition satisfied</p>{{/checkIf}}