首页 > 解决方案 > Django模板中的字符串到整数

问题描述

我在 django 模板中渲染了一个字符串,但在 django 模板中,我想将其转换为整数。我尝试了很多类似 |add:to_int 的方法,但它不起作用。

标签: pythondjangodjango-templates

解决方案


@Vaibhav Mishra,

对你起作用吗?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/

需要在 django 模板中将字符串转换为 int


推荐阅读