1

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.

Pete
  • 57,112
  • 28
  • 117
  • 166
Pratik Nagelia
  • 281
  • 1
  • 4
  • 14

1 Answers1

2

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;
        }
    });
Sandeep Nayak
  • 4,649
  • 1
  • 22
  • 33
  • Thanks for your response ,... But I was looking for an answer in JAVA . Could you please suggest a complete helper in Handlebar.java. – Pratik Nagelia Jun 21 '16 at 06:12
  • Ok, we can use Js Handlebar Helpers in JAVA, by handlebars.registerHelpers(new File("helpers.js")); and it works .But I have no clue how it would affect in production. – Pratik Nagelia Jun 21 '16 at 06:45