我可以向你保证,我已经对我的显示器大喊大叫,并花了几个小时来理解这一点。 首先,我无法理解像 Handlebars 这样不能执行简单比较功能的模板引擎的概念。
无论如何。我有这个辅助函数,当添加到单独的路线时效果很好,正如您在此处看到的那样。不过,我真的很想将其作为全局函数添加到我的 Express 创建的 app.js 文件中。我可以向你保证,辅助函数的 GITHub 示例不起作用。
任何帮助将不胜感激。
我的index.js 文件。
/* GET home page. */
router.get('/', function(req, res, next) {
Coupon.find(function(err, docs)
{
res.render('main/index', {
title: 'Coupon Site new for all',
coupons: docs,
//helpers
helpers: {
eq: function (v1, v2) {
return v1 === v2;
},
ne: function (v1, v2) {
return v1 !== v2;
},
lt: function (v1, v2) {
return v1 < v2;
},
gt: function (v1, v2) {
return v1 > v2;
},
lte: function (v1, v2) {
return v1 <= v2;
},
gte: function (v1, v2) {
return v1 >= v2;
},
and: function (v1, v2) {
return v1 && v2;
},
or: function (v1, v2) {
return v1 || v2;
}
},
});
});
});
在 app.js 中显然我应该能够做这样的事情。文档中没有的内容,我认为我应该以某种方式在我的 index.js
中导入hbs
变量
var hbs = exphbs.create({
// Specify helpers which are only registered on this instance.
helpers: {
foo: function () { return 'FOO!'; },
bar: function () { return 'BAR!'; }
}
});
最佳答案
来自 ExpressHandlebars documentation 的示例:
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');
app.get('/', function (req, res, next) {
res.render('home', {
showTitle: true,
// Override `foo` helper only for this rendering.
helpers: {
foo: function () { return 'foo.'; }
}
});
});
app.listen(3000);
因此,您需要做什么才能为 gt()
、lt()
等提供全局作用域:在 hbs
中声明它们(=== 将它们传递给 exphbs.create()
)变量。
在 render()
中传递 handlebars
属性允许您覆盖在 hbs
中定义的帮助器。
关于javascript - NodeJS/Express/ExpressHandlebars - 全局辅助函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41325523/