physio
physio

Reputation: 129

How do I perform arithmetic operation on a templated type using Jinja2?

I am trying to perform arithmetic operations on a templated datetime value using Jinja2. I looked at the following question: Perform arithmetic operation in Jinja2 and I see that Jinja2 has support for performing arithmetic on templated types.
I want to extend this to datetime.

I tried doing this:

from jinja2 import Template
import datetime
template = Template("Date: {{ currentDate +2  }}")
template.render(currentDate=datetime.datetime.today())

but it throws the following:

TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'int'

I tried thinking of a solution where I can assign a function that, when invoked, returns the date in number of days since the epoch but I still need to be able to represent that value as a valid date.
How do I achieve this using Jinja2?

Upvotes: 3

Views: 172

Answers (1)

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39194

Since your goal is to add two days to another date, you could pass the datetime module to the template, then use its timedelta() method:

Given:

from jinja2 import Template
import datetime

template = Template("""
Date:        {{ currentDate }}
In two days: {{ currentDate + datetime.timedelta(days=2) }}
""")
print(
    template.render(
        currentDate=datetime.datetime.today(), 
        datetime=datetime
    )
)

This would yield:

Date:        2023-01-10 19:52:50.276999
In two days: 2023-01-12 19:52:50.276999

You could even simplify the code further to

from jinja2 import Template
import datetime

template = Template("""
Date:        {{ datetime.datetime.today() }}
In two days: {{ datetime.datetime.today() + datetime.timedelta(days=2) }}
""")
print(
    template.render(datetime=datetime)
)

But remember that a templating system is meant to do the display and you should refrain from doing too much logic in a template.
So, you have to draw the line somewhere between what amount of logic is acceptable in the templates and what is not.

For example, in a MVC, you would probably rather do:

from jinja2 import Template
import datetime

now = datetime.datetime.today()
template = Template("""
Date:        {{ now }}
In two days: {{ in_two_days }}
""")
print(
    template.render(
        now=now,
        in_two_days=now + datetime.timedelta(days=2)
    )
)

Upvotes: 3

Related Questions