Zarif
Zarif

Reputation: 597

Handlebars does not recognize helper

I found this helper online that checks whether a variable is equal to a certain string. I tried to add this helper to my index.hbs file, but I get the following error: Missing helper: "if_eq"

Can someone tell me how I can fix this? I did what they asked me to do in in the official Handlebars docs, so I don't understand. I use NodeJS/Express, but without require('handlebars') or require('express-handlebars'), because that's how express-generator generated it for me.

index.hbs:

<script>
Handlebars.registerHelper('if_eq', function(a, b, opts) {
    if(a == b)
        return opts.fn(this);
    else
        return opts.inverse(this);
});
</script>

{{#each tasks}}
    {{#if_eq status 'unfinished'}}
        [do something]
    {{else}}
        [do something else]
    {{/if_eq}}
{{/each}}

Upvotes: 1

Views: 2501

Answers (1)

Marcos Casagrande
Marcos Casagrande

Reputation: 40434

express-generator uses: hbs package as you can see in here:

enter image description here

So you need to first register the helper in the server side, like this:

const hbs = require('hbs');
const express = require('express');
const app = express();

app.set('view engine', 'hbs');

hbs.registerHelper('if_eq', function(a, b, opts) {
    if(a == b)
        return opts.fn(this);
    else
        return opts.inverse(this);
});
//... rest of your server code

Drop the helper from index.hbs since that's for registering the helper in the client side, and you're rendering handlebars in the server side.

index.hbs

{{#each tasks}}
    {{#if_eq status 'unfinished'}}
        [do something]
    {{else}}
        [do something else]
    {{/if_eq}}
{{/each}}

Upvotes: 1

Related Questions