jinja2 括号中的四舍五入
我想一般来说我很好奇 jinja2 括号中允许哪些操作,例如我想做的是对嵌入数据执行操作,如下所示:
{{ round(255*(mileage['chevy'] - mileage['ford']))/1000 }}
这会在回溯上引发错误:
未定义错误:“圆”未定义
类似地,当我尝试在括号中的 jinja 块中使用 'abs' 时,我收到一个未定义的错误——即使它们都是标准的 lib 函数。有没有某种方法可以在模板渲染期间而不是在传递数据之前执行此操作?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
jinja2 模板语言与 python 语言不同。在 jinja2 中,对值的操作通常在过滤器期间完成:操作}}。您可以在 jinja2 文档中找到过滤器列表。
例如,对于 round,您可以执行以下操作:
这将在网页。
abs
过滤器以同样的方式存在。请注意,这些过滤器只能用于在显示之前更改值,并且可以用于计算。无论如何,计算不应该在模板中完成。
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 :
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.
根据 Jinja Docs [round]
将返回
float
因此结果将为43.0
。如果您需要指定精度,则使用:将返回
42.55
,您也可以选择舍入方法,例如。round(2, 'ceil')
在执行一些数学运算时,也将其放入括号中,例如:
According to Jinja Docs [round]
will returns
float
so result will be43.0
. Iif you need to specify precision use: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:
如果确实需要使用括号样式,可以将所需的函数作为渲染参数传递。
例如,这个小代码:
prints:
您还可以传递模块中的所有函数:
打印:
If you really need to use the parentheses style, you can pass the required functions as rendering parameters.
For example, this small code:
prints:
You can also pass all functions from a module:
which prints: