多个空格键条件运算符

Sin*_*lis 5 meteor spacebars meteor-blaze

有没有办法缩短

{{#if arg1}}
    {{#if arg2}}
        //stuff
    {{/if}}
{{/if}}
Run Code Online (Sandbox Code Playgroud)

只有一个如果?

{{#if arg1 arg2}}
{{#if arg1 && arg2}}
Run Code Online (Sandbox Code Playgroud)

以上两种似乎都不起作用.

Dan*_*scu 8

Spacebars继续将Mustache和Handlebars作为无逻辑模板语言的理念.这就是为什么即使是简单的逻辑也最好放在控制器而不是模板中.

但是,您可以定义执行逻辑的自定义块帮助程序and.

<template name="ifand">
  {{#if arg1}}
    {{#if arg2}}
      {{> Template.contentBlock}}
    {{else}}
      {{> Template.elseBlock}}
    {{/if}}
  {{else}}
    {{> Template.elseBlock}}
  {{/if}}
</template>
Run Code Online (Sandbox Code Playgroud)

呼叫:

{{#ifand arg1="foo" arg2="bar"}}
  // stuff
{{/ifand}}
Run Code Online (Sandbox Code Playgroud)

您还可以了解有关将变量传递到模板的更多信息.

对于一般情况(and在任意数量的参数中),您将要注册一个全局模板帮助器:

Template.registerHelper('and', function () {
  var args = Array.prototype.slice.call(arguments, 0, -1);  // exclude key=value args
  var parameters = arguments[arguments.length - 1];  // key: value arguments

  return _.every(args, function (arg) {
    return !!arg;
  });

});
Run Code Online (Sandbox Code Playgroud)

呼叫:

{{#if and 1 "foo" 3 'bar' param="test"}}
  True
{{else}}
  False
{{/if}}
Run Code Online (Sandbox Code Playgroud)