Sou*_*abh 6 django django-templates django-models django-template-filters
我制作了这个自定义过滤器来检查图像是否存在:
from django import template
from django.core.files.storage import default_storage
register = template.Library()
@register.filter(name='file_exists')
def file_exists(filepath):
    if default_storage.exists(filepath):
        return filepath
    else:
        index = filepath.rfind('/')
        new_filepath = filepath[:index] + '/image.png'
        return new_filepath
我在模板中使用了这个:
<img src="{{ STATIC_URL }}images/{{ book.imageurl }}|file_exists" alt="{{book.title}} Cover Photo">
但它不起作用.我不明白为什么.
您没有应用过滤器,因为|file_exists它不在{{}}.试试这个:
<img src="{{ STATIC_URL }}images/{{ book.imageurl|file_exists }}" alt="{{book.title}} Cover Photo">
或者,如果要应用于file_exists整个图像网址,请尝试以下操作:
<img src="{{ STATIC_URL|add:'images/'|add:book.imageurl|file_exists }}" alt="{{book.title}} Cover Photo">
| 归档时间: | 
 | 
| 查看次数: | 6761 次 | 
| 最近记录: |