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

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


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! :)


One more option:

This way you are setting the moment variable to a local available to all scripts in any EJS page on your site.

In your "index.js" (or "app.js") file do this: (after you have set up your 'app' with Express)

var moment = require('moment');var shortDateFormat = "ddd @ h:mmA"; // this is just an example of storing a date format once so you can change it in one place and have it propagateapp.locals.moment = moment; // this makes moment available as a variable in every EJS pageapp.locals.shortDateFormat = shortDateFormat;

Then in your EJS file you can refer to moment (and shortDateFormat) as variables like this:

<%= moment(Date()).format(shortDateFormat) %>

Perhaps this is slightly more elegant?


var moment = require('moment');app.locals.moment = require('moment');

Use in the view:

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

Now you can simply use moment in your EJS files.