【问题标题】:How to display current year in Flask template?如何在 Flask 模板中显示当前年份?
【发布时间】:2017-05-05 00:26:27
【问题描述】:

我正在寻找如何在 Flask 模板中输出当前年份。我知道在 Django 中你可以使用 {% now "Y" %}.,但是有 Flask 等价物吗?到目前为止,我在研究期间一直找不到任何东西。

【问题讨论】:

    标签: python datetime templates flask


    【解决方案1】:

    使用template context processor 将当前日期传递给每个模板,然后呈现其year 属性。

    from datetime import datetime
    
    @app.context_processor
    def inject_now():
        return {'now': datetime.utcnow()}
    
    {{ now.year }}
    

    如果您在大多数模板中不需要它,也可以使用 render 传递对象。

    return render_template('show.html', now=datetime.utcnow())
    

    【讨论】:

      【解决方案2】:

      暂时有Flask Moment。它像 Moment 一样强大,并且在 Flask 中易于使用。要在 Jinja 模板中以用户的本地时间显示年份:

      <p>The current year is: {{ moment().format('YYYY') }}.</p>
      

      【讨论】:

        【解决方案3】:

        您可以像这样使用像 moment.js 这样的 JavaScript 库:

        <script>
        document.write(moment("2012-12-31T23:55:13 Z").format('LLLL'));
        </script>
        

        【讨论】:

        • 我建议在 Jinja 中这样做是为了兼容性,而不是在 JS 中,但如果你不能这样做:&lt;script&gt;document.write(new Date().getFullYear())&lt;/script&gt; 不需要库。
        • @Blaise 我正在使用烧瓶,老实说这似乎是最好的方法。只需将其显示在前端即可。计算年份并在后端传递似乎很麻烦。
        猜你喜欢
        • 2011-09-09
        • 2011-09-04
        • 2013-12-20
        • 1970-01-01
        • 2019-12-03
        • 2012-12-25
        • 1970-01-01
        • 2017-10-22
        • 2012-09-27
        相关资源
        最近更新 更多