Question

Assuming I have two variables "one" and "two" where they equal 1 and 2 respectively. How can I divide them in a mako template if possible? I want something like:

${"{0:.2f}".format(one/two)}

The result I want to output in the template is: 0.50

I am using python 2.x.

Was it helpful?

Solution

You need to add division to future_imports argument of the Template:

>>> from mako.template import Template
>>> print Template("${a/b}").render(a=1, b=2)
0
>>> print Template("${a/b}", future_imports=['division']).render(a=1, b=2)
0.5
>>> print Template("${'{0:.2f}'.format(a/b)}", future_imports=["division"]).render(a=1, b=2)
0.50

Quote from docs:

future_imports – String list of names to import from __future__. These will be concatenated into a comma-separated string and inserted into the beginning of the template, e.g. futures_imports=['FOO', 'BAR'] results in from __future__ import FOO, BAR. If you’re interested in using features like the new division operator, you must use future_imports to convey that to the renderer, as otherwise the import will not appear as the first executed statement in the generated code and will therefore not have the desired effect.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top