javascript - NodeJS/Express/ExpressHandlebars - 全局辅助函数

标签 javascript node.js express handlebars.js handlebarshelper

我可以向你保证,我已经对我的显示器大喊大叫,并花了几个小时来理解这一点。 首先,我无法理解像 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/

相关文章:

javascript - 如何从 Asp.Net MVC Razor 将值设置为 HTML5 日期字段?

node.js - 如何注册多个 grunt-exec 任务?

javascript - 访问本地主机:3000 through localhost/myproject/index. html

node.js - Mongoose 数组 indexOf 无法正常工作

node.js - 运行 Express 时 Socket.IO 无法连接到服务器

javascript - 如何使用 gecko 浏览器引擎在 C# 中单击 anchor 标记

javascript - 从 CoffeeScript 调用 JavaScript "new"

javascript - 如何在 JavaScript 中按下键并将其放入数组中?

node.js - 使用 AWS api 网关 + lambda + Nodejs 的私有(private)和公共(public) ip

javascript - 获取文档后从 Firestore 获取文档 ID