首页 > django > 在regexp模板中使用django cut过滤器

在regexp模板中使用django cut过滤器 (Using django cut filter in template with regexp)

问题

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

我想知道是否有一些使用正则表达式与切割过滤器,因为我还没有找到一种方法这样做。

我想要做的一个例子:

{{ instance.image_url|cut:"/images/products/*/dl_img/" }}'

Where *指的是各种目录名,例如bedstables

有一种简单的方法可以在模板中执行此操作吗?

解决方法

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

# 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)

然后像使用它一样

{% load cut_re %}
{{ instance.image_url|cut_re:"/images/products/.*/dl_img/" }}

问题

I have URLs that all end with an image filename. I am trying to strip all of the URL except the filename, however the URL path can vary, as I have images in different directories.

I am wondering if there is someway to use regexp with the cut filter, as I have not found a way to do so yet.

An example of what I am trying to do:

{{ instance.image_url|cut:"/images/products/*/dl_img/" }}'

Where * refers to various directory names, such as beds or tables

Is there an easy way to do this in a template?

解决方法

You can make your own custom template filter:

# 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)

And then use it like

{% load cut_re %}
{{ instance.image_url|cut_re:"/images/products/.*/dl_img/" }}
相似信息