Search code examples
handlebars.jshandlebarshelperhandlebars.java

Handlebar.java : Comparing equality in #if helpers


How can I compare equality and other logical conditions in Handlebars.java. For example:

{{#if template_version == "v2" }}
  //do something 
{{ else }}
  //do something
{{/if}}

Solutions with or without registerHelper() are welcome.


Solution

  • You need to write a helper to do the == check, as Handlebars dosen't provide the == construct out-of-box.

    You could write a simple helper like this:

        Handlebars.registerHelper('if_eq', function(a, b, opts) {
    
            if(a == b) // Or === depending on your needs
                return opts.fn(this);
            else
                return opts.inverse(this);
        });
    

    You can give the helper any name. I have given if_eq.

    Now, in your template:

    {{#if_eq template_version "v2" }}
      //do something 
    {{ else }}
      //do something
    {{/if_eq}}
    

    Incase, you want helpers for all the operators out there, you could do something like below:

        Handlebars.registerHelper({
            eq: function (v1, v2) {    
                return v1 === v2;
            },
            ne: function (v1, v2) {
                return v1 !== v2;
            },
            lt: function (v1, v2) {
                return v1 < v2;
            },
            gt: function (v1, v2) {
                return v1 > v2;
            },
            lte: function (v1, v2) {
                return v1 <= v2;
            },
            gte: function (v1, v2) {
                return v1 >= v2;
            },
            and: function (v1, v2) {
                return v1 && v2;
            },
            or: function (v1, v2, opts) {
                return v1||v2;
            }
        });