首页 > 解决方案 > 带有标签自定义过滤器的 django 模板

问题描述

我有一个dict包含图像的列表。关键是ida 的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。我该如何正确地做到这一点?

标签: djangodjango-templates

解决方案


在模板过滤器中,您不需要使用额外的双花括号,您可以这样写:

{% with imagelist=images|dictvalue:journey.id %}

话虽如此,在模板中实现业务逻辑通常不是一个好主意。通常在视图中执行此操作。


推荐阅读