【发布时间】:2020-04-15 07:31:22
【问题描述】:
我在 django 模板中渲染了一个字符串,但在 django 模板中,我想将其转换为整数。我已经尝试了很多类似 |add:to_int 的方法,但它不起作用。
【问题讨论】:
标签: python django django-templates
我在 django 模板中渲染了一个字符串,但在 django 模板中,我想将其转换为整数。我已经尝试了很多类似 |add:to_int 的方法,但它不起作用。
【问题讨论】:
标签: python django django-templates
@Vaibhav 米什拉,
它对你有用吗? https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#add
点赞:{% value|add:"0" %}
如果它不适合你:然后创建一个自定义模板过滤器并注册它:
YOUR_APP_FOLDER/
__init__.py
models.py
templatetags/
__init__.py
your_app_name_extras.py [any valid filename.py]
views.py
在 your_app_name_extras.py
中from django import template
register = template.Library()
@register.filter()
def to_int(value):
return int(value)
在你的模板文件中,你需要把代码:
{% load your_app_name_extras %}
{{ value|to_int }}
更多详情:
https://docs.djangoproject.com/en/3.0/howto/custom-template-tags/
【讨论】: