Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 798
maxm Avatar asked Oct 06 '11 14:10

maxm


People also ask

How do you make a loop in Jinja2?

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.

How are variables in Jinja2 templates specified?

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.


2 Answers

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.

like image 148
madjar Avatar answered Oct 04 '22 21:10

madjar


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) }}
like image 26
rozumir Avatar answered Oct 04 '22 21:10

rozumir