从 Meteor 中的 Handlebars 模板内部格式化日期 [英] Format a date from inside a Handlebars Template in Meteor

查看:22
本文介绍了从 Meteor 中的 Handlebars 模板内部格式化日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

像这样:

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

我正在使用 moment 库,所以我可以这样写:

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.

推荐答案

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

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.

对于这个例子,我只使用了short"和long",但你会看到,它很容易扩展.

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

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

So I created an Object in my Client Script:

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

此外,我创建了一个 Handlebars HelperformatDate".

Also, I created a Handlebars Helper "formatDate".

已现在您应该使用 UI 而不是 Handlebars

Edited: Now you should use UI instead of 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;
  }
});

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

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

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

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

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

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

快乐编码!

这篇关于从 Meteor 中的 Handlebars 模板内部格式化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆