Search code examples
javascriptnode.jsconditional-statementshandlebars.jsexpress-handlebars

Basic 'if' statements do not work in handlebars JS


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?


Solution

  • 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.