首页 > 解决方案 > 检查变量是数字 django 模板

问题描述

嗨,我想检查我的变量在 Django 模板中是否为数字,我尝试了这段代码

{% if isnumeric(item) %}
<h1>{{item}}</h1>
{% endif %}

但这给我带来了这个错误

无法解析余数:来自 'isnumeric(item)' 的 '(item)'

我试图在 Django 文档的此页面https://docs.djangoproject.com/en/3.1/ref/templates/builtins/中找到内置模板标签或过滤器

我也在 StackOverflow 中搜索过这个问题,但我没有找到任何相关的东西

标签: djangodjango-templates

解决方案


我不相信有一个内置的模板函数来检查它。一种方法是编写自己的:

https://docs.djangoproject.com/en/3.1/howto/custom-template-tags/

代码看起来像:

my_filters.py

from django import template
register = template.Library()
@register.filter()
def is_numberic(value):
    return value.isdigit()

在html中:

{% load my_filters %}

{% if item|is_numeric %}
    ...

推荐阅读