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

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

    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();
    });
    

提交回复
热议问题