To use MomentJS in views/custom.ejs, what is the correct way (if any)?
Server side
routes/index etc we can easily use require(\'moment\');
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.
You can create the function and attach it to the app.locals. and use it in the ejs template on the server side.
In your routes file you do
../routes/page.js
var ejs = require('ejs')
, moment = require('moment');
app.locals.fromNow = function(date){
return moment(date).fromNow();
}
../views/page.ejs
<span class="created_at"><%= fromNow(item.created_at) %></span>
Just remember to have moment added to to your package.json file
I wrote a helpers to return moment for using on ejs
view and layouts.
./helpers/utils/get-moment.js
const moment = require('moment');
module.exports = {
friendlyName: 'formatMoney',
description: 'format money number.',
inputs: {},
sync: true,
exits: {},
fn: function (inputs, exits) {
return exits.success(moment);
}
};
Then using:
const moment = sails.helpers.utils.getMoment();
As of Node v12.8.3, it seems that you can pass require
directly to EJS templates, i.e. this works:
const ejs = require('ejs')
let renderedHTML = ejs.render(`<% const moment = require('moment') %>`, { require })