Django:如何构建一个endswith模板过滤器

Oma*_*les 2 python django jinja2

如果以结尾,我需要渲染图像adobe_illustrator_file_logo.pngfile.url.ai

但如果file.url以其他终止方式结束,.png例如 example,我将渲染该对象的图像。

我已经搜索过文档,但显然没有endswith内置过滤器。

所以我最终玩了ifequals过滤slice器。

逻辑是相同的:“如果字符串与最后 3 个字母相同,则执行此操作”。

但是,它不起作用,因为没有显示任何内容。

<td>
   {% ifequal cart_item.file.url|default:""|slice:"-3" ".ai" %}

        <img src="{% static 'img/admin/adobe_illustrator_file_logo.png' %}"
                   alt=""
                   class="float-left rounded custom_image">
   {% endifequal %}
 </td>
Run Code Online (Sandbox Code Playgroud)

笔记:

<p>{{ cart_item.file.url  }}</p>
Run Code Online (Sandbox Code Playgroud)

HTML 呈现

<p>/media/files/working_precisely.ai</p>
Run Code Online (Sandbox Code Playgroud)

此外,如果将adobe_illustrator_file_logo.png放在 if 条件之外,它也会正确呈现。

更新1:

创建了我自己的过滤器,但出现错误:

/cart/
endswith 处的 TemplateSyntaxError 需要 2 个参数,已提供 1 个

from django import template
from django.template.defaultfilters import stringfilter

register = template.Library()

@register.filter(is_safe=False)
@stringfilter
def endswith(value, suffix):
    return value.endswith(suffix)
Run Code Online (Sandbox Code Playgroud)

模板

{% if cart_item.file.url|endswith: ".ai" %}

       <img src="{% static 'img/admin/adobe_illustrator_file_logo.png' %}"
                alt=""
                class="float-left rounded custom_image">
{% endif %}
Run Code Online (Sandbox Code Playgroud)

ben*_*kji 5

您不需要(另一个)自定义过滤器,您几乎已经拥有它了。你用 python|slice:"-3"做了一个切片,但你想要一个切片。所以,稍微明确一点:[:-3][-3:]

{% if object.image.url.lower|slice:"-3:" == "gif" %}
  # note the added : in "-3:", to make it a [-3:]
{% endif %}
Run Code Online (Sandbox Code Playgroud)

虽然它不是一个真正的endswith,严格来说(因为如果你的结尾值改变长度,即 4,如果检查“jpeg”,你将必须调整你的切片长度),但工作得很好,不需要添加另一个模板过滤器到你的项目。