Skip to main content
 首页 » 编程设计

python之如何使用 mako 模板进行划分

2024年11月01日10arxive

假设我有两个变量“一”和“二”,它们分别等于 1 和 2。如果可能的话,我怎样才能把它们分成一个 mako 模板?我想要这样的东西:

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

我要在模板中输出的结果是:0.50

我正在使用 python 2.x。

请您参考如下方法:

您需要将 division 添加到 Template 的 future_imports 参数:

>>> 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 

引自 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.