django - 检查变量是数字 django 模板
问题描述
嗨,我想检查我的变量在 Django 模板中是否为数字,我尝试了这段代码
{% if isnumeric(item) %}
<h1>{{item}}</h1>
{% endif %}
但这给我带来了这个错误
无法解析余数:来自 'isnumeric(item)' 的 '(item)'
我试图在 Django 文档的此页面https://docs.djangoproject.com/en/3.1/ref/templates/builtins/中找到内置模板标签或过滤器
我也在 StackOverflow 中搜索过这个问题,但我没有找到任何相关的东西
解决方案
我不相信有一个内置的模板函数来检查它。一种方法是编写自己的:
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 %}
...
推荐阅读
- node.js - 多个端口上的节点 nginx 代理,同一个域不起作用
- php - 由于缓存,Laravel 无法提交表单
- javascript - NodeJS + 电子路径
- postgresql - Postgresql:如何使用 Barman 进行增量备份
- javascript - Grafana 5插件开发,如何保存用户数据/面板状态?
- jquery - jquery ajax 没有创建 golang 会话 cockie
- angular - Angular 5 - 在方法中使用选定的选项
- json - JSON.parse 返回对象对象
- mysql - MYSQL索引一张表进行统计
- wordpress - 错误:获取 https://registry-1.docker.io/v2/:net/http:在等待连接时取消请求 - Docker 与 Wordpress