3

I am using express-handlebars and have the following minimal template:

<!DOCTYPE html>
<html>

    <body>

        {{#if page === 'help'}}YAAAY{{/if}}

    </body>
</html>

This fails to parse with:

Error: C:\Users\mike\myapp\views\error.hbs: Parse error on line 6:
...ody>     {{#if page === 'help'}}YAAAY{{/i
---------------------^

I understand handlebars isn't expecting an ===, but isn't that the point of if?

How can I use an if statement in handlebars?

mikemaccana
  • 81,787
  • 73
  • 317
  • 396
  • Try `==` instead. – Code-Apprentice Aug 20 '18 at 15:17
  • 1
    Handlerbars have if only for checking if value is true or false it's not if like in javascript for this you will need to created your own helper. – jcubic Aug 20 '18 at 15:19
  • 3
    Wow: https://stackoverflow.com/a/16315366/1225328. I'm curious to know the reasoning behind this "no boolean operator" choice they made to be honest. – sp00m Aug 20 '18 at 15:20
  • @sp00m care to post another answer with this link or edit my answer? Think it's very helpful in this context ;-) – Lyubomir Aug 20 '18 at 15:24
  • @lustoykov Feel free to edit your answer, I don't have much credits here :) The best might actually be to mark this question as duplicate, what do you think @mikemaccana? – sp00m Aug 20 '18 at 15:26
  • @sp00m Views should be as dumb as possible. Computation should be done elsewhere. – Dave Newton Aug 20 '18 at 15:31
  • @DaveNewton Makes sense, looks like the above link actually breaks this principle... What would then be a better approach for the OP's case in your opinion? Also, one could ask why views have `if`s in the first place then... Looks like having entirely logicless views is a bit utopian (depending on the definition of "logic") :) – sp00m Aug 20 '18 at 15:55
  • 1
    @sp00m There's an `if`, it's already not logic-less. The point is to minimize the amount of computation in views, as it's almost always easier to test that logic outside of templates (and that logic has a tendency to accrete, making it even harder). – Dave Newton Aug 20 '18 at 15:57

2 Answers2

5

Handlebar's if-helper only accepts a boolean as an argument. You have two options:

Use the existing handler

Pass the result from page === 'help' as a variable in the template and do something like:

{{#if isPageHelp}}
  <h1> Help! </h1>
{{/if}}

Make your own handler

You can implement the === operator with your own handler. Thanks @sp00m.

mikemaccana
  • 81,787
  • 73
  • 317
  • 396
Lyubomir
  • 17,533
  • 4
  • 51
  • 65
1

Try this helpers

 const Handlebars = require('handlebars');
    Handlebars.registerHelper('ifCond', function (v1,v2,options) {
    if (v1 == v2)
        return options.fn(this);
    else
        return options.inverse(this);
    });

Handlebars.registerHelper('exCond', function (v1,v2,options) {
    if (v1 != v2)
        return options.fn(this);
    else
        return options.inverse(this);
});
Chin2
  • 41
  • 1
  • 4