Jinja2中如何实现这个帖子多久前发布的?

2012 年 12 月 18 日
 kenneth
@livid
1.如何实现像v2ex这样,记录的是一个DateTime()的时间,如何得到3天前发布, 2小时前发布这样的。
2.如何实现nl2br()这样的,因为直接显示数据库的数据换行处理的好像不好。
7368 次点击
所在节点    Tornado
18 条回复
Brutal
2012 年 12 月 18 日
Brutal
2012 年 12 月 18 日
unixtools
2012 年 12 月 18 日
kenneth
2012 年 12 月 18 日
@Brutal 能否详细说下,因为思路有了,具体怎么搞还是不懂。
ergatea
2012 年 12 月 18 日
@kenneth unixtools同学给的例子非常清楚了。
kenneth
2012 年 12 月 18 日
@ergatea
@unixtools
@Brutal

我在模板中想用{{locale.formate(comment.created_at)}}为什么不行?
ipconfiger
2012 年 12 月 18 日
写个filter
kenneth
2012 年 12 月 18 日
@livid 能否给个解答?
Brutal
2012 年 12 月 18 日
@kenneth 要是要在 jinja2 中实现,将给你的代码写成 filter ,然后
{{comment.created_at | timesince }} 就可以了
kenneth
2012 年 12 月 18 日
@Brutal 在tornado中如何写?Flask和Tornado不通用吧。
Brutal
2012 年 12 月 18 日
@kenneth 没研究过 tornado 和 jinja2 整合,
那你就把那个单独弄成函数 timesince(t) 然后传变量 timesince(comment.created_at)
kenneth
2012 年 12 月 18 日
我现在用的是{{locale.format_date(comment.created_at)}}
可是只能出现 December 18, 2012 at 11:31 pm
这个是绝对时间,并不是相对时间。
tunetoystory
2012 年 12 月 18 日
我是用时间戳之差判断的,多少以内返回秒,然后返回分钟,往后推到最后直接返回具体时间
SErHo
2012 年 12 月 18 日
http://timeago.yarp.com/ 试试这个?
kenneth
2012 年 12 月 19 日
@Brutal @Rabbit52 @unixtools @ergatea @ipconfiger @SErHo @livid
应该用的不是这个方法吧。我看文档
format_date(date, gmt_offset=0, relative=True, shorter=False, full_format=False)
By default, we return a relative time (e.g., “2 minutes ago”). You can return an absolute date string with relative=False.

默认应该返回,起码也应该是2 minutes ago这种,为什么我的显示是 December 18, 2012 at 11:29 pm
也就是绝对时间,而不是相对时间呢?不知道错哪里了?
killall
2012 年 12 月 19 日
http://jinja.pocoo.org/docs/api/#custom-filters

写一个filter, 将你的时间作为参数放到自己写的filter里面计算将结果进行返回
filter里面就是将时间跟当前时间比对,计算出来多少天就可以了。
貌似jq也有直接渲染的插件。
kenneth
2012 年 12 月 19 日
今天一早醒来,竟然变了 4 hours ago
Livid
2012 年 12 月 19 日
数据库里存 unix timestamp,然后在显示的时候,用当前的 unix timestamp 减去之前存的,然后差值就是中间经过的秒数。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://study.congcong.us/t/55240

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX