maxm
maxm

Reputation: 5371

Rounding in jinja2 brackets

I guess just generally I'm curious about what operations are allowable in jinja2 brackets, e.g. what I'm trying to do is perform an operation on embedded data like so:

{{ round(255*(mileage['chevy'] - mileage['ford']))/1000 }}

This throws the error on traceback:

UndefinedError: 'round' is undefined

Similarly when I try to use 'abs' in a bracketed jinja block, I get an Undefined error--even though they're both standard lib functions. Is there some way to perform this operation during template-rendering, rather than before passing the data?

Upvotes: 14

Views: 28901

Answers (3)

rozumir
rozumir

Reputation: 905

According to Jinja Docs [round]

{{ 42.55|round }}

will returns float so result will be 43.0. Iif you need to specify precision use:

{{ 42.55321|round(2) }}

will return 42.55, also you can choose method of rounding, eg. round(2, 'ceil')

also when performing some math operations take it into brackets like:

{{ (x*y/z)|round(2) }}

Upvotes: 4

Mostafa Farzán
Mostafa Farzán

Reputation: 1003

If you really need to use the parentheses style, you can pass the required functions as rendering parameters.

For example, this small code:

from jinja2 import Environment, BaseLoader

mytemplate = '{{ round(3.7) }}'
result = Environment(loader=BaseLoader).from_string(mytemplate).render(round=round)
print(result)

prints:

4

You can also pass all functions from a module:

from jinja2 import Environment, BaseLoader
import math
from inspect import getmembers

mytemplate = '{{ fabs(sin(-pi/3)) }}'
result = Environment(loader=BaseLoader).from_string(mytemplate).render(getmembers(math))
print(result)

which prints:

0.8660254037844386

Upvotes: -1

madjar
madjar

Reputation: 12951

The jinja2 templating language is different from the python language. In jinja2, operation on values are often done during filters : {{ something | operation }}. You can find a list of filters in the jinja2 documentation.

For example, to round, you can do :

{{ 42.55|round }}

This will display "42" on the web page. A abs filter exist in the same way.

Please note that these filters can only be used to alter values before display, and can be used for calculations. Calculations shouldn't be done in the template anyway.

Upvotes: 38

Related Questions