Rahul Mangal
Rahul Mangal

Reputation: 475

Want to compare two string in handlebars view in node js app

I want to do some comparisons in a handlebars template in an express-nodejs app.

It looks something like this:

{{# if(x==y)}}
    equal string
 {{else}}
    not equal string
 {{/if}}

I already installed the handlebars and express-handlebars packages. I read about the handlebars helpers but couldn't figure out a way to use them properly. I tried to add the helpers in the app.js file in my app, but I couldn't use them in my template file in view.

Any help would be helpful and appreciated.

Thanks

Upvotes: 0

Views: 5472

Answers (1)

Hadrien TOMA
Hadrien TOMA

Reputation: 2733

You can use the is function like this :

 {{#is x "my_string"}}
     x is "my_string"
 {{else}}
     x isn't "my_string"
 {{/is}}

Otherwise, you can use this famous helper :

Handlebars.registerHelper('if_equal', function(a, b, opts) {
    if (a == b) {
        return opts.fn(this)
    } else {
        return opts.inverse(this)
    }
})

And use it like this :

{{#if_equal x "my_string"}}
     x is "my_string"
{{else}}
     x isn't "my_string"
{{/if_equal}}

Upvotes: 3

Related Questions