【问题标题】:String to Integer in Django TemplateDjango模板中的字符串到整数
【发布时间】:2020-04-15 07:31:22
【问题描述】:

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

【问题讨论】:

标签: python django django-templates


【解决方案1】:

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

Need to convert a string to int in a django template

【讨论】:

    猜你喜欢
    • 2013-07-09
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 2016-06-09
    • 2016-01-29
    • 1970-01-01
    • 2012-06-06
    • 2017-07-17
    相关资源
    最近更新 更多