5

有没有办法缩短

{{#if arg1}}
    {{#if arg2}}
        //stuff
    {{/if}}
{{/if}}

只是一个如果?

{{#if arg1 arg2}}
{{#if arg1 && arg2}}

以上两种方法似乎都不起作用。

4

2 回答 2

8

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

但是,您可以定义一个自定义块助手来执行逻辑and.

<template name="ifand">
  {{#if arg1}}
    {{#if arg2}}
      {{> Template.contentBlock}}
    {{else}}
      {{> Template.elseBlock}}
    {{/if}}
  {{else}}
    {{> Template.elseBlock}}
  {{/if}}
</template>

调用为:

{{#ifand arg1="foo" arg2="bar"}}
  // stuff
{{/ifand}}

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

对于一般情况(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;
  });

});

调用为:

{{#if and 1 "foo" 3 'bar' param="test"}}
  True
{{else}}
  False
{{/if}}
于 2014-11-04T21:35:24.010 回答
1

在模板中,您可以使用this对象来引用传入的参数,这让我避免在大多数需要它们的情况下使用多个#if 参数。

Template.myTemplate.created = function() {
    if(this.data.arg1 && this.data.arg2) {
        //do JS setup here
    }
}

此外,可以使用指定助手

Template.registerHelper('exists', function() {
    if(this.data.arg1 && this.data.arg2) {
        return true
    }
}

并且您执行上述帮助程序

{{#if exists}}
    //stuff
{{/if}}

{{> myTemplate arg1 arg2}}

我只是偶然发现了这个,但这对我来说是一个巨大的发现。

于 2014-11-04T21:56:15.700 回答