如何在EJS視圖中使用節點模塊(如MomentJS)?

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


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

要在views / custom.ejs中使用MomentJS,正確的方法是什么(如果有的話)?

  1. Server side

    服務器端

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

    路線/索引等我們可以輕松使用require('moment');等,它工作正常。

  2. Server Side (EJS views)

    服務器端(EJS視圖)

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

    views / custome.ejs,類似<%var m = require('moment'); %>不起作用

I am using ExpressJS with EJS as the template engine.

我使用ExpressJS和EJS作為模板引擎。

9 个解决方案

#1


48  

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).
  • 更好的ejs使用(沒有|管道)。

On your controller, or view.js do this:

在您的控制器上,或view.js執行此操作:

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:

現在你可以在你的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! :)

我不是節點專家,所以如果有人看到這樣做的不好,請告訴我! :)

#2


17  

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.

這樣,您可以將moment變量設置為站點上任何EJS頁面中所有腳本可用的本地變量。

In your "index.js" (or "app.js") file do this: (after you have set up your 'app' with Express)

在您的“index.js”(或“app.js”)文件中執行以下操作:(在使用Express設置“app”之后)

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:

然后在你的EJS文件中你可以將moment(和shortDateFormat)稱為變量,如下所示:

<%= moment(Date()).format(shortDateFormat) %>

Perhaps this is slightly more elegant?

也許這稍微優雅一點?

#3


10  

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

我使用ejs在服務器端使用時刻。我寫了一個將從現在返回的ejs過濾器函數。

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

#4


7  

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.

現在您只需在EJS文件中使用時刻即可。

#5


2  

How about passing down require like this:

傳遞下來要求如下:

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

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.

顯然這只適用於Node(后端)。

#6


1  

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

您在上面提到的服務器端(EJS視圖)在瀏覽器上運行而不在您的服務器上運行。您無法使用require,因為瀏覽器無法理解它。您需要導入moment.js才能使用它

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

#7


1  

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

您可以創建該功能並將其附加到app.locals。並在服務器端的ejs模板中使用它。

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

只記得將時刻添加到package.json文件中

#8


0  

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

#9


0  

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

我寫了一個幫助器來返回在ejs視圖和布局上使用的時刻。

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

然后使用:

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/10/09/7258fa2a70f2ca6660a2f34f3546f41e.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com