试图格式化玉模板上的日期

bab*_*eii 17 node.js pug

我有一个index.js:

exports.index = function(req, res){
  db.courses.find(function(err, currentCourses) {
    res.render('index', {
      currentCourses: currentCourses
    });
  });
};
Run Code Online (Sandbox Code Playgroud)

在我的玉模板上:

tr
    td #{currentCourses[0].start}
Run Code Online (Sandbox Code Playgroud)

这是一个日期,格式为"Sun Sep 29 2013 00:00:00 GMT + 0100(BST)".

如何将其格式化为"2013年9月29日"?

编辑(在Ed Hinchliffe的评论之后):

-function prettyDate(dateString){
    -var d = date.getDate(dateString);
    -var monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
    -var m = monthNames[date.getMonth()];
    -var y = date.getFullYear();
    -return d+' '+m+' '+y;
-} 
for course in currentCourses
    tr
        td #{prettyDate(course.start)}
Run Code Online (Sandbox Code Playgroud)

小智 56

我的解决方案是:

momentjs添加到您的快速应用程序本地,如下所示:
app.locals.moment = require('moment');

然后你可以在任何玉文件中使用时刻:
span='(Created at: ' + moment(obj.createTime).format("YYYY/MM/DD") + ')'

参考:
在服务器端Jade模板中使用实用程序库


Ed *_*ffe 10

不幸的是,不是特别容易.您需要一个函数来在模板内部或外部格式化字符串(并传递漂亮的字符串).

像这样的东西(JADE)

-function prettyDate(dateString){
    //if it's already a date object and not a string you don't need this line:
    -var date = new Date(dateString);
    -var d = date.getDate();
    -var monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
    -var m = monthNames[date.getMonth()];
    -var y = date.getFullYear();
    -return d+' '+m+' '+y;
-}


tr
   td #{prettyDate(currentCourses[0].start)}
Run Code Online (Sandbox Code Playgroud)


mor*_*ore 6

胡志峰的上述解决方案给了我正确的方向。不幸的是 app.locals.moment 对我不起作用。

但是您也可以将require('moment') 也直接传递到模板属性的对象中。

var data = {
  title: 'some nice title',
  updateDate: new Date(),
  ....,
  moment: require( 'moment' )
};
Run Code Online (Sandbox Code Playgroud)

然后像往常一样将数据对象传递给模板函数。

var template = pug.compile( source );
var html = template( data );
Run Code Online (Sandbox Code Playgroud)

源文件示例:

doctype html
html
  head
    title= title
  body
    div= moment(updateDate).format('YYYY-MM-DD')
Run Code Online (Sandbox Code Playgroud)