Conditional statements with multiple spaces

Is there any way to cut

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

to one if?

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

Both of the above do not work.

+5
source share
2 answers

Spacebars continues the philosophy of Mustache and Handlebars, which are not logical template languages. That's why even simple logic fits best in a controller, not a template.

However, you can define a custom helper block that performs a logical and .

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

Call as:

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

You can also learn about passing variables to templates .

In the general case ( and among an arbitrary number of arguments) you will want to register a global template helper:

 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; }); }); 

Call as:

 {{#if and 1 "foo" 3 'bar' param="test"}} True {{else}} False {{/if}} 
+7
source

Inside the template, you can use the this object to refer to the arguments passed, which allows me to avoid using multiple #if arguments in most cases in which I need them.

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

Helpers can also be specified using

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

and you execute the above helper as such

 {{#if exists}} //stuff {{/if}} {{> myTemplate arg1 arg2}} 

I accidentally stumbled upon this by accident, but this is a HUGE find for me.

+1
source

Source: https://habr.com/ru/post/1206200/


All Articles