javascript 从 Meteor 中的 Handlebars 模板内部格式化日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18580495/
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-10-27 12:27:34  来源:igfitidea点击:

Format a date from inside a Handlebars Template in Meteor

javascriptdatetimemeteorhandlebars.jsdate-format

提问by Boris Kotov

I got a ISO formatted Date from my Data and what I actually want to do, is to modify my date format directly from my Templates.

我从我的数据中得到了一个 ISO 格式的日期,而我真正想做的是直接从我的模板中修改我的日期格式。

like this:

像这样:

{{format my.context.date "myFormat"}}

I'm using the moment library, so I could write something like this:

我正在使用时刻库​​,所以我可以写这样的东西:

{{formatDate my.context.date "DD.MM.YYYY HH:mm"}} // 03.09.2013 18:12

It would be nice, because I think it's the place where I should be able to do this. In my template.

这会很好,因为我认为这是我应该能够做到的地方。在我的模板中。

回答by Boris Kotov

The solution is quite simple, and maybe someone will find it useful. In most projects you have a couple of date formats you want to use. So it's a good approach to define your formats with readable names.

解决方案非常简单,也许有人会发现它很有用。在大多数项目中,您有几种要使用的日期格式。因此,使用可读名称定义格式是一种很好的方法。

For this example I took just 'short' and 'long', but you will see, it's very easy to extend.

在这个例子中,我只使用了“short”和“long”,但是你会看到,它很容易扩展。

So I created an Object in my Client Script:

所以我在我的客户端脚本中创建了一个对象:

var DateFormats = {
       short: "DD MMMM - YYYY",
       long: "dddd DD.MM.YYYY HH:mm"
};

Also, I created a Handlebars Helper "formatDate".

另外,我创建了一个 Handlebars Helper“formatDate”。

Edited: Now you should use UI instead of Handlebars

编辑:现在你应该使用 UI 而不是 Handlebars

// Deprecated since version 0.8.0 
Handlebars.registerHelper("formatDate", function(datetime, format) {

// Use UI.registerHelper..
UI.registerHelper("formatDate", function(datetime, format) {
  if (moment) {
    // can use other formats like 'lll' too
    format = DateFormats[format] || format;
    return moment(datetime).format(format);
  }
  else {
    return datetime;
  }
});

As you can see, I use the moment.js lib in my Helper. To install it, just type meteor add momentjs:momentfrom your command line.

如您所见,我在 Helper 中使用了 moment.js 库。要安装它,只需meteor add momentjs:moment从命令行输入。

And now, everywhere in my Templates I can use it with the two params, like this:

现在,在我的模板中的任何地方,我都可以将它与两个参数一起使用,如下所示:

{{formatDate MyISOString "short"}} // 02 September - 2013
{{formatDate MyISOString "long"}} //  Monday 02.09.2013 18:00

If you want to create your own formats, take a look at the momentjs docs http://momentjs.com/docs/

如果您想创建自己的格式,请查看 momentjs 文档http://momentjs.com/docs/

Happy coding!

快乐编码!