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?
Jinja2 being a templating language has no need for wide choice of loop types so we only get for loop. For loops start with {% for my_item in my_collection %} and end with {% endfor %} . This is very similar to how you'd loop over an iterable in Python.
A Jinja template doesn't need to have a specific extension: . html , . xml , or any other extension is just fine. A template contains variables and/or expressions, which get replaced with values when a template is rendered; and tags, which control the logic of the template.
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.
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) }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With