Reputation: 1315
I am looking to find out how to output the current year in a Flask template. I know in Django you can use {% now "Y" %}.
, but is there a Flask equivalent? I have been unable to find anything during my research thus far.
Upvotes: 32
Views: 23988
Reputation: 15
If using Jinja2 is too cumbersome and you are using Jinja2
in a context of a browser that you can simply use Javascript.
<span id="year"></span>
const year = document.querySelector('#year');
if (year) {
year.innerHTML = new Date().getFullYear().toString();
}
<script>
document.write(moment("2012-12-31T23:55:13 Z").format('LLLL'));
</script>
Upvotes: -7
Reputation: 127190
Use a template context processor to pass the current date to every template, then render its year
attribute.
from datetime import datetime
@app.context_processor
def inject_now():
return {'now': datetime.utcnow()}
{{ now.year }}
Or pass the object with render
if you don't need it in most templates.
return render_template('show.html', now=datetime.utcnow())
Upvotes: 74
Reputation: 1482
For moment there is Flask Moment. It is powerful like Moment, and easy to use in Flask. To display the year in the user's local time from your Jinja template:
<p>The current year is: {{ moment().format('YYYY') }}.</p>
Upvotes: 6