Tornado Documentation
› http://www.v2ex.com/tornado/
Tornado on GitHub
› https://github.com/facebook/tornado/
Tornado Gists
› http://tornadogists.org/
kenneth
V2EX  ›  Tornado

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

  •  
  •   kenneth · Dec 18, 2012 · 7981 views
    This topic created in 5072 days ago, the information mentioned may be changed or developed.
    @livid
    1.如何实现像v2ex这样,记录的是一个DateTime()的时间,如何得到3天前发布, 2小时前发布这样的。
    2.如何实现nl2br()这样的,因为直接显示数据库的数据换行处理的好像不好。
    18 replies  •  1970-01-01 08:00:00 +08:00
    kenneth
    kenneth
    OP
    Dec 18, 2012
    4
    @Brutal 能否详细说下,因为思路有了,具体怎么搞还是不懂。
    ergatea
    ergatea
    Dec 18, 2012
    5
    @kenneth unixtools同学给的例子非常清楚了。
    kenneth
    kenneth
    OP
    Dec 18, 2012
    6
    @ergatea
    @unixtools
    @Brutal

    我在模板中想用{{locale.formate(comment.created_at)}}为什么不行?
    ipconfiger
    ipconfiger
    Dec 18, 2012
    7
    写个filter
    kenneth
    kenneth
    OP
    Dec 18, 2012
    8
    @livid 能否给个解答?
    Brutal
    Brutal
    Dec 18, 2012
    9
    @kenneth 要是要在 jinja2 中实现,将给你的代码写成 filter ,然后
    {{comment.created_at | timesince }} 就可以了
    kenneth
    kenneth
    OP
    Dec 18, 2012
    10
    @Brutal 在tornado中如何写?Flask和Tornado不通用吧。
    Brutal
    Brutal
    Dec 18, 2012
    11
    @kenneth 没研究过 tornado 和 jinja2 整合,
    那你就把那个单独弄成函数 timesince(t) 然后传变量 timesince(comment.created_at)
    kenneth
    kenneth
    OP
    Dec 18, 2012
    12
    我现在用的是{{locale.format_date(comment.created_at)}}
    可是只能出现 December 18, 2012 at 11:31 pm
    这个是绝对时间,并不是相对时间。
    tunetoystory
    tunetoystory
    Dec 18, 2012
    13
    我是用时间戳之差判断的,多少以内返回秒,然后返回分钟,往后推到最后直接返回具体时间
    SErHo
    SErHo
    Dec 18, 2012
    14
    http://timeago.yarp.com/ 试试这个?
    kenneth
    kenneth
    OP
    Dec 19, 2012
    15
    @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
    killall
    Dec 19, 2012
    16
    http://jinja.pocoo.org/docs/api/#custom-filters

    写一个filter, 将你的时间作为参数放到自己写的filter里面计算将结果进行返回
    filter里面就是将时间跟当前时间比对,计算出来多少天就可以了。
    貌似jq也有直接渲染的插件。
    kenneth
    kenneth
    OP
    Dec 19, 2012
    17
    今天一早醒来,竟然变了 4 hours ago
    Livid
    Livid
    MOD
    PRO
    Dec 19, 2012
    18
    数据库里存 unix timestamp,然后在显示的时候,用当前的 unix timestamp 减去之前存的,然后差值就是中间经过的秒数。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1591 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 50ms · UTC 08:43 · PVG 16:43 · LAX 00:43 · JFK 03:43
    ♥ Do have faith in what you're doing.