Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: Missing helper: "if_equal" handlebars

Tags:

I tried to register handlebar on my express node application, but seems like it doesn't work

const express = require('express');
const hbs = require('hbs');
const expressHbs = require('express-handlebars');

const app = express();
app.engine('.hbs', expressHbs({ defaultLayout: 'layout', extname: '.hbs' }));
app.set('view engine', 'hbs');

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

In .hbs file I run this code

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

Then I received this error

Error: Missing helper: "if_equal" handlebars

like image 251
sinusGob Avatar asked May 15 '17 11:05

sinusGob


1 Answers

The problem is that you're using two different view engines. express-handlebars & hbs.

Your .hbs files are being rendered with express-handlebars, while you're registering the helper to hbs.

Using hbs

Drop express-handlebars, and drop this line:

app.engine('.hbs', expressHbs({ defaultLayout: 'layout', extname: '.hbs' }));

The extension .hbs is the default one for hbs:

Using hbs as the default view engine requires just one line of code in your app setup. This will render .hbs files when res.render is called.

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

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

Using express-handlebars

//remove require('hbs');
const expressHbs = require('express-handlebars');

const hbs = expressHbs.create({
    // Specify helpers which are only registered on this instance.
    helpers: {
        if_equal: function(a, b, opts) {
            if (a == b) {
                return opts.fn(this)
            } else {
                return opts.inverse(this)
            }
        }

    }
});

//The following example sets up an Express app to use 
//.hbs as the file extension for views:
app.engine('.hbs', expressHbs({extname: '.hbs'}));
app.set('view engine', '.hbs'); //with dot
like image 154
Marcos Casagrande Avatar answered Sep 21 '22 10:09

Marcos Casagrande