user855443
user855443

Reputation: 2940

How to insert the current date with jinja2

I am new to use Jinja2 and try to insert the current date in a document as a bottom line to tell users when the document was produced.

My current solution is

Produced on {{ utils.today|date('%x') }} There are no error messages, but nothing is produced.

The solution need to be Jinja2 only, as I have no python process running - using Ginger (a Haskell program) to process the template.

Upvotes: 3

Views: 18175

Answers (2)

Micah Smith
Micah Smith

Reputation: 4471

Jinja2 doesn't have native support for inserting the date. However, you can easily prepare the date in whatever library you use to render the template and pass the value to the rendering function.

Using jinja2 in Python:

import datetime
date = datetime.date.today()
template = Template('Produced on {{ date }}')
template.render(date=date)

If you are using Ginger, you would have the same template, just make sure to create the date in Haskell and render the template with that value.

You can also write or install a jinja2 extension that will make utilities for working with dates available in the template.

For example, after installing jinja2-time [1], your template would look like this:

Produced on {% now 'local' %}

[1]: untested code

Upvotes: 1

Viseshini Reddy
Viseshini Reddy

Reputation: 819

Context Processors can be used to inject values into templates before rendering it.

In app.py:

import datetime

@app.context_processor
def inject_today_date():
    return {'today_date': datetime.date.today()}

And add this in the html file:

<p>{{today_date}}</p>

Output: 2019-01-07

Upvotes: 3

Related Questions