我在把手中注册自定义助手时遇到问题。 我尝试过任何我能找到但没有任何作用的东西。
这是我在app.js中的内容
const express= require('express');
const exphbs = require('express-handlebars');
var socket = require('socket.io')
const app=express();
const querystring = require('querystring');
var hbs = exphbs.create({
extname: '.hbs',
defaultLayout: 'default',
layoutsDir: './lib/templates/layouts',
partialsDir: './lib/templates/partials',
helpers: require("./helpers/handlebars.js").helpers
});
app.engine('hbs', hbs.engine);
//Handlebars Middleware
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
app.use(express.static('public'));
我有helpers / handlebars.js这段代码:
var register = function (Handlebars) {
var helpers = {
formatCurrency: function (currency) {
return currency.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
},
format_date: function (date, format) {
return moment(date).format(format);
}
};
if (Handlebars && typeof Handlebars.registerHelper === "function") {
for (var prop in helpers) {
Handlebars.registerHelper(prop, helpers[prop]);
}
} else {
return helpers;
}
};
module.exports.register = register;
module.exports.helpers = register(null);
(这是我在网上找到的一个例子)
但是当我转到我的观点并尝试打电话给这个帮手时:
{{formatCurrency settings.Ngames}}
我收到此错误:
Error: Missing helper: "formatCurrency"
我已尝试在app.js中的Handlebars.register中使用,但它无法识别Handlebars。
我做错了什么?我如何注册帮助者?
谢谢!
答案 0 :(得分:1)
您应该注册Handlebar助手。
发布我的完整代码:
const express = require('express');
const exphbs = require('express-handlebars');
const app = express();
var hbs = exphbs.create({
extname: '.hbs',
defaultLayout: 'default',
layoutsDir: './lib/templates/layouts',
partialsDir: './lib/templates/partials'
});
require("./helpers/handlebars").register(hbs.handlebars);
app.engine('hbs', hbs.engine);
//Handlebars Middleware
app.engine('handlebars', exphbs({ defaultLayout: 'main' }));
app.set('view engine', 'handlebars');
app.use(express.static('public'));
const router = express.Router();
router.get("/hello", function (req, res) {
res.render("index", { layout: false });
});
app.use(router);
app.listen(8080);
帮助文件:
var register = function (Handlebars) {
var helpers = {
formatCurrency: function (currency) {
return currency.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
},
format_date: function (date, format) {
return moment(date).format(format);
}
};
if (Handlebars && typeof Handlebars.registerHelper === "function") {
for (var prop in helpers) {
Handlebars.registerHelper(prop, helpers[prop]);
}
} else {
return helpers;
}
};
module.exports.register = register;