操作顺序 Django 模板
Order of Operations Django Templates
我在 Django 模板中有一个浮点变量 mynumber
,我需要将它四舍五入到最接近的整数 没有第三方过滤器 ,所以我正在关注这个逻辑:
int(mynumber - 0.5) + 1
在 Django 模板中我可以这样做:
{{ mynumber|add:"-0.5"|add:"1" }}
但是如您所见,问题是没有运算顺序,所以我得到的数字与预期的不同,我该如何解决?没找到插入括号的方法,第一次运算后还需要转成整数
But the problem, as you can see, is that there is no order of operations.
问题是您从不在某处调用 int
。 add
模板过滤器是 implemented as [GitHub]:
@register.filter(is_safe=False) def add(value, arg):
"""Add the arg to the value."""
try:
return <b>int(</b>value<b>)</b> + <b>int(</b>arg<b>)</b>
except (ValueError, TypeError):
try:
return value + arg
except Exception:
return ''
所以它将首先在值和操作数上投int
,因为0.5
无法转换为 int
,它将 return 为空字符串。
and I need to round it to the nearest integer without third party filters.
好消息是,有一个内置的模板过滤器可以做到这一点:|floatformat
[Django-doc]。正如文档所说:
If used with a numeric integer argument, floatformat
rounds a number to that many decimal places. (…) Particularly useful is passing 0 (zero) as the argument which will round the float to the nearest integer.
所以你可以渲染它:
{{ mynumber<b>|floatformat:"0"</b> }}
我在 Django 模板中有一个浮点变量 mynumber
,我需要将它四舍五入到最接近的整数 没有第三方过滤器 ,所以我正在关注这个逻辑:
int(mynumber - 0.5) + 1
在 Django 模板中我可以这样做:
{{ mynumber|add:"-0.5"|add:"1" }}
但是如您所见,问题是没有运算顺序,所以我得到的数字与预期的不同,我该如何解决?没找到插入括号的方法,第一次运算后还需要转成整数
But the problem, as you can see, is that there is no order of operations.
问题是您从不在某处调用 int
。 add
模板过滤器是 implemented as [GitHub]:
@register.filter(is_safe=False) def add(value, arg): """Add the arg to the value.""" try: return <b>int(</b>value<b>)</b> + <b>int(</b>arg<b>)</b> except (ValueError, TypeError): try: return value + arg except Exception: return ''
所以它将首先在值和操作数上投int
,因为0.5
无法转换为 int
,它将 return 为空字符串。
and I need to round it to the nearest integer without third party filters.
好消息是,有一个内置的模板过滤器可以做到这一点:|floatformat
[Django-doc]。正如文档所说:
If used with a numeric integer argument,
floatformat
rounds a number to that many decimal places. (…) Particularly useful is passing 0 (zero) as the argument which will round the float to the nearest integer.
所以你可以渲染它:
{{ mynumber<b>|floatformat:"0"</b> }}