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

前端 未结 10 1744
耶瑟儿~
耶瑟儿~ 2020-12-14 00:03

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\');

10条回答
  •  孤街浪徒
    2020-12-14 00:42

    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:

    
        

    <%= moment().fromNow() %>

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

提交回复
热议问题