如果adobe_illustrator_file_logo.png以.ai结尾,我需要渲染图像.ai。
但是,如果file.url以其他终端结束,比如.png作为示例,我将呈现对象的图像。
我已经搜索了文档,但显然没有内置过滤器的endswith。
所以我最后玩了ifequals和slice过滤器。
逻辑是一样的:“如果字符串与最后三个字母相同,就这样做”。
但是,它不起作用,因为什么都不显示。
<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:
创建了自己的过滤器,但是gettting错误:
TemplateSyntaxError at /cart/
_**endswith requires 2 arguments, 1 provided**_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 %}发布于 2021-02-11 10:52:30
您不需要(另一个)自定义过滤器,您几乎已经拥有它。您的|slice:"-3"在python中做了一个[:-3]切片,但是您想要一个[-3:]切片。因此,只需稍微明确一点:
{% if object.image.url.lower|slice:"-3:" == "gif" %}
# note the "-3:"
# sidenote: arbitry code snippet from my current project...
{% endif %}https://stackoverflow.com/questions/54428668
复制相似问题