我正在尝试为Handlerbars实现自己的帮助器,但我无法弄清楚我需要注册它的位置,以便我可以在我的模板中访问它。 我总是得到失踪的帮手:“abcde”
我在这里检查了很多相同的问题但是没有成功。
这是我的app.js:
var express = require('express');
var handlebars = require('handlebars');
var expresshandlebars = require('express-handlebars');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', expresshandlebars({ defaultLayout: 'main', layoutsDir: path.join(__dirname, 'views/layouts') }));
app.set('view engine', 'handlebars');
handlebars.registerHelper('abcde',
function (str) {
return str;
}
);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '../../site')));
app.use('/', index);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
以下是我在main.handlebars布局文件中使用模板的方法:
<a href="/" class="item">{{abcde "test"}}</a>
答案 0 :(得分:0)
你尝试过这种技术吗?从这里https://www.npmjs.com/package/express-handlebars
var express = require('express');
var exphbs = require('express-handlebars');
var app = express();
var hbs = exphbs.create({
// Specify helpers which are only registered on this instance.
helpers: {
foo: function () { return 'FOO!'; },
bar: function () { return 'BAR!'; }
}
});
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
无论哪种方式,我都会专注于在你的快速手柄上设置助手,而不是你的把手变量。