无法注册车把助手
Posted
技术标签:
【中文标题】无法注册车把助手【英文标题】:can't register handlebar helpers 【发布时间】:2018-05-07 07:40:43 【问题描述】:我在把手中注册自定义助手时遇到问题。 我已经尝试了我能找到的任何东西,但没有任何效果。
这是我在 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。
我做错了什么?如何注册助手?
谢谢!
【问题讨论】:
【参考方案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;
【讨论】:
以上是关于无法注册车把助手的主要内容,如果未能解决你的问题,请参考以下文章