node.js - 如何在 EJS View 中使用 Node 模块(如 MomentJS)?

标签 node.js express ejs momentjs

要在views/custom.ejs 中使用MomentJS,正确的方法是什么(如果有的话)?

  1. 服务器端

    路线/索引等我们可以轻松使用require('moment');等等,它工作正常。

  2. 服务器端(EJS View )

    views/custome.ejs,类似于 <% var m = require('moment'); %>不工作

我使用 ExpressJS 和 EJS 作为模板引擎。

最佳答案

我找到了另一种方法,我认为它有一些优势。

  • 不要污染您的代码导出过滤器。
  • 无需全部导出即可访问任何方法。
  • 更好地使用 ejs(无 | 管道)。

在您的 Controller 或 view.js 上执行以下操作:

var moment = require('moment');
exports.index = function(req, res) {
    // send moment to your ejs
    res.render('index', { moment: moment });
}

现在你可以在你的 ejs 中使用 moment:

<html>
    <h1><%= moment().fromNow() %></h1>
</html>

我不是 Node 专家,所以如果有人发现这样做有什么不好的地方,请告诉我! :)

关于node.js - 如何在 EJS View 中使用 Node 模块(如 MomentJS)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12794860/

相关文章:

javascript - 类型错误 : object is not a function In Node JS/socket. io

javascript - 如何使用 MongoDB 更改数组的顺序?

node.js - EJS-将多个单词作为值添加到搜索栏

javascript - 在 .ejs 文件中获取当前页面?

javascript - 无法启动我的服务器,因为 TypeError

Node.js BDD。 cucumber 、小 cucumber 还是 cucumber ?

node.js - 为什么我的请求在循环时会被暂停?

node.js - Nexmo 不在 node.js 中发送短信

node.js - Nodejs + Express : make http request wait for udp response

node.js - 为什么这个 if/else 在 ejs 中不起作用?