python - Django模板中的字符串到整数
问题描述
我在 django 模板中渲染了一个字符串,但在 django 模板中,我想将其转换为整数。我尝试了很多类似 |add:to_int 的方法,但它不起作用。
解决方案
@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/
推荐阅读
- c# - 如何在 ASP.NET Core 2.1 网站上启用 HttpOnly cookie
- .net - 如何使用“DetectLocalizedObjects”?
- codeigniter - codeigniter 在单独的字段中上传 2 个文件(图像和视频)
- html - 使用uikit的图像叠加悬停效果
- java - 通过 EventChannel 向 Flutter 发送 Android SMS BroadcastReceiver 数据
- jquery - 选中父复选框时,仅检查没有子子项的直接子项
- c# - 如何在asp net core中的服务之间共享websocket
- android - Android UDP 故障导致 VOIP 口吃
- java - 拥有@ApplicationScoped bean 效率更高吗?
- plasticscm - PlasticSCM:对未决更改进行深入比较