I’m using Jinja on my site and I like it.
I’ve come across a simple need. How to display today’s date? Is there a way to inline some Python code in a Jinja template?
import datetime
now = datetime.datetime.utcnow()
print now.strftime("%Y-%m-%d %H:%M")
This article says no, but suggests using a macro or a filter?
Really? Must we resort to all that? OK, what would that look like in this case?
No, there is no way to inline Python into Jinja. However, you can add to the constructs that Jinja knows by extending the Environment of the template engine or the global namespace available to all templates. Alternately, you can add a filter that let’s you format datetime objects.
Flask stores the Jinja2 Environment on
app.jinja_env. You can inject new context into the environment by either adding to this dictionary directly, or by using the@app.context_processordecorator.Whatever path you choose, this should be done while you are setting up the application, before you have served any requests. (See the snippets section of the website for some good examples of how to set up filters – the docs contain a good example of adding to the global variables).