Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Spacebar Conditional Operators

Is there a way to shorten

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

to just a single if?

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

Both of the above don't seem to work.

like image 536
Sinistralis Avatar asked Nov 04 '14 21:11

Sinistralis


2 Answers

Spacebars continues the philosophy of Mustache and Handlebars being logic-less template languages. This is why even simple logic is best placed in the controller rather than in the template.

You can, however, define a custom block helper 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 more about passing variables into templates.

For the general case (and among an arbitrary number of arguments), you'll 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}}
like image 70
Dan Dascalescu Avatar answered Nov 08 '22 10:11

Dan Dascalescu


While within a template, you are able to use the this object to reference arguments passed in, which lets me avoid having to use multiple #if arguements in most of the cases I need them in.

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

Additionally, helpers can 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 just stumbled on this by accident but this is a HUGE find for me.

like image 32
Sinistralis Avatar answered Nov 08 '22 11:11

Sinistralis