Error: no helper: handle "if_equal"

I tried registering the handle of my express node application, but it looks like it is not working

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 the .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 got this error

Error: Missing helper: "if_equal" handlebars

+4
source share
1 answer

The problem is that you are using two different viewing mechanisms. express-handlebars and hbs .

Your files are .hbsdisplayed using express-handlebars, while you register the assistant before hbs.

Using hbs

Drop express-handlebarsand leave this line:

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

.hbs hbs:

hbs . .hbs res.render.

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)
    }
});

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
+3

Source: https://habr.com/ru/post/1677168/


All Articles