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

前端 未结 10 1723
耶瑟儿~
耶瑟儿~ 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:47

    I use moment on the server side with ejs. I wrote an ejs filter function that will return fromNow.

    npm install moment
    

    ./views/page.ejs

    <%=: item.created_at | fromNow %>
    

    ./routes/page.js

    var ejs = require('ejs')
      , moment = require('moment');
    
    ejs.filters.fromNow = function(date){
      return moment(date).fromNow()
    }
    

提交回复
热议问题