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

前端 未结 10 1703
耶瑟儿~
耶瑟儿~ 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 01:00
    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.

    0 讨论(0)
  • 2020-12-14 01:01

    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

    0 讨论(0)
  • 2020-12-14 01:01

    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();
    
    0 讨论(0)
  • 2020-12-14 01:01

    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 })
    
    0 讨论(0)
提交回复
热议问题