【问题标题】:Django: how to build an endswith filterDjango:如何构建一个endswith过滤器
【发布时间】: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" %}

标签: python django jinja2


【解决方案1】:

您不需要(其他)自定义过滤器,您几乎已经拥有它。你的 |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 %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    • 2021-08-31
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多