【发布时间】:2017-05-05 00:26:27
【问题描述】:
我正在寻找如何在 Flask 模板中输出当前年份。我知道在 Django 中你可以使用 {% now "Y" %}.,但是有 Flask 等价物吗?到目前为止,我在研究期间一直找不到任何东西。
【问题讨论】:
标签: python datetime templates flask
我正在寻找如何在 Flask 模板中输出当前年份。我知道在 Django 中你可以使用 {% now "Y" %}.,但是有 Flask 等价物吗?到目前为止,我在研究期间一直找不到任何东西。
【问题讨论】:
标签: python datetime templates flask
使用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())
【讨论】:
暂时有Flask Moment。它像 Moment 一样强大,并且在 Flask 中易于使用。要在 Jinja 模板中以用户的本地时间显示年份:
<p>The current year is: {{ moment().format('YYYY') }}.</p>
【讨论】:
您可以像这样使用像 moment.js 这样的 JavaScript 库:
<script>
document.write(moment("2012-12-31T23:55:13 Z").format('LLLL'));
</script>
【讨论】:
<script>document.write(new Date().getFullYear())</script> 不需要库。