作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我尝试在我的 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
呈现。
放下 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)
}
});
//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/
我尝试在我的 express node 应用程序上注册 handlebar,但它似乎不起作用 const express = require('express'); const hbs = requi
我是一名优秀的程序员,十分优秀!