使用正则表达式在模板中使用 django 剪切过滤器

Jak*_*kin 1 django django-templates

我的 URL 都以图像文件名结尾。我试图删除除文件名之外的所有 URL,但是 URL 路径可能会有所不同,因为我在不同的目录中有图像。

我想知道是否有办法将 regexp 与 cut 过滤器一起使用,因为我还没有找到这样做的方法。

我正在尝试做的一个例子:

{{ instance.image_url|cut:"/images/products/*/dl_img/" }}'
Run Code Online (Sandbox Code Playgroud)

where*指的是各种目录名称,例如beds或tables

有没有一种简单的方法可以在模板中做到这一点?

Ber*_*ant 5

您可以制作自己的自定义模板过滤器:

# templatetags/cut_re.py
import re 

from django import template
register = template.Library()

@register.filter
def cut_re(value, search): 
    return re.sub(search, "", value)
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它

{% load cut_re %}
{{ instance.image_url|cut_re:"/images/products/.*/dl_img/" }}
Run Code Online (Sandbox Code Playgroud)