Search code examples
meteormeteor-blazespacebars

More elegant helper for Meteor 0.9.3 templates


I've created a custom block helper for Meteor 0.9.3 using information from the following URL: https://github.com/meteor/meteor/wiki/Using-Blaze#new-pattern-for-defining-custom-block-helpers

It can be used within a Spacebars template like so:

{{#ifEqual value1="stringOrNumber_1" value2="stringOrNumber_2"}}
  <h1>The values ARE equal!</h1>
{{else}}
  <h1>The values are NOT equal!</h1>
{{/ifEqual}}

Here is the code:

<template name="ifEqual">
  {{#if isEqual value1 value2}}
    {{> UI.contentBlock}}
  {{else}}
    {{> UI.elseBlock}}
  {{/if}}
</template>

Template.ifEqual.isEqual = function (value1, value2) {
  return value1 === value2;
};

My question is:

Is there a possible way to make this less clunky?

I would much prefer code that can be used within a template like so:

{{#ifEqual "stringOrNumber_1" "stringOrNumber_2"}}
...

Solution

  • I would register a global equals helper:

    Template.registerHelper('equals', function(value1, value2){
        return value1 === value2
    })
    

    And then use it like this:

    {{#if equals "abc" "abc"}}
        <p>They're equal :)</p>
    {{else}}
        <p>They're not equal :(</p>
    {{/if}}
    

    Though, you may be interested in using the underscore-helper package instead, so you don't have to define this (and similar) helpers yourself.