django - 带有标签自定义过滤器的 django 模板
问题描述
我有一个dict
包含图像的列表。关键是id
a 的journey
。现在我想得到一个基于 id 的图像列表,所以我写了一个过滤器:
@register.filter
def dict_value(dict, key):
return dict.get(key)
现在我想使用这个过滤器,但是如何使用呢?这就是我所做的:
{% for journey in journeys %}
...
{% with imagelist={{ images|dictvalue:{{journey.id}} }} %}
{% if imagelist %}
<img class="card-img-top" data-src="" style="height: 225px; width: 100%; display: block;" src="{{imagelist.0.url}}" data-holder-rendered="true">
{% else %}
<img class="card-img-top" data-src="" style="height: 225px; width: 100%; display: block;" src="https://via.placeholder.com/348x225.png" data-holder-rendered="true">
{% endif %}
{% endwith %}
...
{% endfor %}
为了测试,如果列表不为空,我想显示第一张图片。
但我有一个问题with-tag
。我该如何正确地做到这一点?
解决方案
在模板过滤器中,您不需要使用额外的双花括号,您可以这样写:
{% with imagelist=images|dictvalue:journey.id %}
话虽如此,在模板中实现业务逻辑通常不是一个好主意。通常在视图中执行此操作。
推荐阅读
- angular - 如何通过自定义指令动态添加组件
- android - Kotlin 的瞬态?
- go - go/types: Config.Check 找不到包
- git - 我在 stash 中创建了一个 PR,该 pr 有多个提交,并且为了压缩它们存在冲突问题
- javascript - 使用 hapi/Joi 的 Express JS 表单验证无法正确验证表单数据
- asp.net-core - 如何从 mvc 核心中的操作返回预压缩数据?
- java - HttpUrlConnection:从非 200OK 获取响应正文
- c# - DDD - 领域模型和实体继承
- java - 如果启动时没有可用的代理,Spring Integration Kafka 3.0.1 -> 3.1.2 测试现在无法启动
- vb.net - 如何在 vb.net 中使用状态码 429“请求过多”