gpt4 book ai didi

javascript - 错误 : Missing helper: "if_equal" handlebars

转载 作者:搜寻专家 更新时间:2023-10-31 23:15:56 25 4
gpt4 key购买 nike

我尝试在我的 express node 应用程序上注册 handlebar,但它似乎不起作用

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

在 .hbs 文件中我运行这段代码

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

然后我收到这个错误

Error: Missing helper: "if_equal" handlebars

最佳答案

问题是您使用了两个不同的 View 引擎。 express-handlebars & hbs .

当您将助手注册到 hbs 时,您的 .hbs 文件正在使用 express-handlebars 呈现。

使用 hbs

放下 express-handlebars,然后放下这一行:

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

扩展名 .hbs 是 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)
}
});

使用快速 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

关于javascript - 错误 : Missing helper: "if_equal" handlebars,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43978972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com