Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
888 views
in Technique[技术] by (71.8m points)

node.js - How to use node modules (like MomentJS) in EJS views?

To use MomentJS in views/custom.ejs, what is the correct way (if any)?

  1. Server side

    routes/index etc we can easily use require('moment'); etc and it works fine.

  2. Server Side (EJS views)

    views/custome.ejs, something like <% var m = require('moment'); %> doesn't work

I am using ExpressJS with EJS as the template engine.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found another way of doing this, and I think it has some advantages.

  • Don't polute your code exporting filters.
  • Access any method without the need to export them all.
  • Better ejs usage (no | pipes).

On your controller, or view.js do this:

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

Now you can use moment inside your ejs:

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

I'm not an Node expert, so if anyone see something bad on doing this, let me know! :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...