gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:57:11 25 4
gpt4 key购买 nike

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

但是,如果 file.url 以其他终止符结尾,例如 .png 例如,我将渲染该对象的图像。

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

所以我最终使用了 ifequalsslice 过滤器。

逻辑是相同的:“如果字符串与最后 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>

注意:

<p>{{ cart_item.file.url  }}</p>

HTML 呈现:

<p>/media/files/working_precisely.ai</p>

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

更新1:

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

/cart/处的模板语法错误
endwith 需要 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)

模板

{% 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 %}

最佳答案

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

{% if object.image.url.lower|slice:"-3:" == "gif" %}
# note the added : in "-3:", to make it a [-3:]
# sidenote: arbitry code snippet from my current project...
{% endif %}

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

关于python - Django:如何构建一个endswith模板过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54428668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com