0

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

1 Answer 1

3

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}}
Sign up to request clarification or add additional context in comments.

10 Comments

Thanks @hardrien for helping me. Where do i put the registerHelper either in app.js or router js file(index.js)
Wherever you want in a JavaScript that will be executed client side ;) (but after loading the handlebar.js library)
you mean i should put the Handlebars.registerHelper('if_equal', function(a, b, opts){..........} in template file?
Only just after the script that loads handlebar.js.
TypeError: expressHbs.registerHelper is not a function at Object.<anonymous> (F:\xampp\htdocs\node-todo\app.js:29:12) at Module._compile (module.js:556:32) at Object.Module._extensions..js (module.js:565:10) at Module.load (module.js:473:32) at tryModuleLoad (module.js:432:12) at Function.Module._load (module.js:424:3) at Module.require (module.js:483:17) at require (internal/module.js:20:19) ..................... ......................... [nodemon] app crashed - waiting for file changes before starting...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.