【发布时间】:2019-01-29 19:51:33
【问题描述】:
如果file.url 以.ai 结尾,我需要渲染图像adobe_illustrator_file_logo.png。
但如果 file.url 以其他终止方式结束,例如 .png,我将渲染对象的图像。
我正在搜索文档,但显然没有 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>
注意:
<p>{{ cart_item.file.url }}</p>
HTML 呈现:
<p>/media/files/working_precisely.ai</p>
此外,如果将 adobe_illustrator_file_logo.png 置于 if 条件之外,则可以正确呈现。
更新 1:
创建了我自己的过滤器,但出现错误:
/cart/处的TemplateSyntaxError
endswith 需要 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 %}
【问题讨论】:
-
有一个关于创建自定义过滤器的详尽文档:docs.djangoproject.com/en/2.2/howto/custom-template-tags/…
-
您可以write your own filter。事实上,你可以在底层使用像
os.path.splitext()这样的 Python 东西来拆分扩展并返回任何必要的内容(False、True 或标识类型的自定义字符串)。 -
@xyres 请看我的更新。
-
你能举一个
cart_item.file.url的示例值 -
算了,我刚看到你的问题。只需删除过滤器和传递值之间的空格。所以它变成了
{% if cart_item.file.url|endswith:".ai" %}