Express使用hbs模板注册ifCond自定义helper报Missing helper错误如何解决
错误原因
你直接在原生Handlebars库实例上注册自定义helper,但是Express使用的hbs模板引擎模块内部维护了独立的Handlebars实例,你在外部原生Handlebars上注册的辅助函数不会被hbs模板引擎识别,所以渲染模板时会提示Missing helper: "ifCond"。
修复方案
修改app.js中Handlebars引入和helper注册的逻辑即可:
- 替换原生Handlebars引入为
hbs模块引入 - 调用
hbs模块提供的registerHelper方法注册自定义辅助函数
修正后的完整app.js代码
const express = require('express') const app = express() // 替换为引入hbs模块,而非原生handlebars const hbs = require('hbs') todolist = [ { task: 'Task 1', status: 'Todo' }, { task: 'Task 2', status: 'In Progress' } ] // 用hbs的registerHelper方法注册自定义helper hbs.registerHelper("ifCond", function(key, value, options) { return (key==value) ? options.fn(this) : options.inverse(this) }) app.use(express.urlencoded({extended:true})) app.set('view engine', 'hbs') app.get('/', (req, res)=>{ res.render('index', { title: 'Todolist', todolist }) }) app.post('/', (req,res)=>{ todolist.push({ task: req.body.task, status:req.body.status }) res.redirect('/') }) app.listen(1111, ()=>{ console.log('server started at http://localhost:1111') })
修改完成后重启服务即可正常识别ifCond辅助函数。
内容的提问来源于stack exchange,提问作者Shubhanshu Singh
相关产品推荐
相关产品推荐

