短くする方法はありますか
{{#if arg1}}
{{#if arg2}}
//stuff
{{/if}}
{{/if}}
単一のifに?
{{#if arg1 arg2}}
{{#if arg1 && arg2}}
上記の両方が機能していないようです。
短くする方法はありますか
{{#if arg1}}
{{#if arg2}}
//stuff
{{/if}}
{{/if}}
単一のifに?
{{#if arg1 arg2}}
{{#if arg1 && arg2}}
上記の両方が機能していないようです。
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}}
テンプレート内では、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}}
たまたま見つけたのですが、これは私にとって大きな発見です。