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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12794860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:26:59  来源:igfitidea点击:

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

node.jsexpressejsmomentjs

提问by dmodulus

To use MomentJS in views/custom.ejs, what is the correct way (if any)?

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');etc and it works fine.

  2. Server Side (EJS views)

    views/custome.ejs, something like <% var m = require('moment'); %>doesn't work

  1. Server side

    routes/index etc we can easily use require('moment');etc and it works fine.

  2. Server Side (EJS views)

    views/custome.ejs, something like <% var m = require('moment'); %>doesn't work

I am using ExpressJS with EJS as the template engine.

I am using ExpressJS with EJS as the template engine.

回答by robertomarin

I found another way of doing this, and I think it has some advantages.

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).
  • 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:

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:

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

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

回答by Matt Manuel

One more option:

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.

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)

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 propagate
app.locals.moment = moment; // this makes moment available as a variable in every EJS page
app.locals.shortDateFormat = shortDateFormat;

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

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?

Perhaps this is slightly more elegant?

回答by Mostafa Darezereshki

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

Use in the view:

Use in the view:

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

Now you can simply use moment in your EJS files.

Now you can simply use moment in your EJS files.

回答by chovy

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

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

./views/page.ejs

<span class="created_at"><%=: item.created_at | fromNow %></span>

./routes/page.js

./routes/page.js

var ejs = require('ejs')
  , moment = require('moment');

ejs.filters.fromNow = function(date){
  return moment(date).fromNow()
}

回答by haxpanel

How about passing down requirelike this:

How about passing down requirelike this:

res.render('index', { require: require });

You might need to tweak to maintain the path:

You might need to tweak to maintain the path:

res.render('index', { require: module => require(module /* here you may insert path correction */) });

Obviously this works with Node (backend) only.

Obviously this works with Node (backend) only.

回答by user2125268

You can create the function and attach it to the app.locals. and use it in the ejs template on the server side.

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

In your routes file you do

../routes/page.js

../routes/page.js

var ejs = require('ejs')
  , moment = require('moment');

app.locals.fromNow = function(date){
  return moment(date).fromNow();
}

../views/page.ejs

../views/page.ejs

<span class="created_at"><%= fromNow(item.created_at) %></span>

Just remember to have moment added to to your package.json file

Just remember to have moment added to to your package.json file

回答by Vinoth

The server side (EJS views) which you mentioned above is running on browser and not on your server. You cannot use require because browsers cannot understand it. You need to import the moment.js to use it

The server side (EJS views) which you mentioned above is running on browser and not on your server. You cannot use require because browsers cannot understand it. You need to import the moment.js to use it

<script src="/js/moment.min.js"></script>

回答by phuong nguyen

I wrote a helpers to return moment for using on ejsview and layouts.

I wrote a helpers to return moment for using on ejsview and layouts.

./helpers/utils/get-moment.js

./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:

Then using:

const moment = sails.helpers.utils.getMoment();

回答by Fareed Alnamrouti

also i think it is good idea if you want you can add a middle-ware where you can add anything you want to the theme layer including user,config and moment:

also i think it is good idea if you want you can add a middle-ware where you can add anything you want to the theme layer including user,config and moment:

// config, user, moment to the theme layer
app.use(function (req, res, next) {
    // grab reference of render
    var _render = res.render;
    // override logic
    res.render = function (view, options, fn) {
        // extend config and continue with original render
        options = options || {};
        options.config = config;
        options.moment = moment;
        if (req.user && req.user.toJSON) {
            options.user = req.user.toJSON();
        }
        _render.call(this, view, options, fn);
    }
    next();
});