easy-thumbnail 包的注册标签过滤器没有以直接从静态目录呈现图像的方式实现。相反,它需要 Image/FileField 模型 (Doc Reference) 的实例。但是您可以实现自己的过滤器,将 url 重定向到静态目录并根据您的需要使用它。
在这里,您也可以采用以下策略之一。
{% load static thumbnail %}
{% thumbnail image 50x50 crop="center" as thumb %}
{% if thumb %}
<img src="{{ STATIC_URL }}{{ thumb.url }}" width="{{ thumb.width }}" height="{{ thumb.height }}" alt="" />
{% else %}
<img src="{{ STATIC_URL }}img/V.png" alt=""/>
{% endif %}
或
{% load static thumbnail %}
{% thumbnail object.image|default:'{{ STATIC_URL }}img/V.png' 50x50 %}
如果您对静态文件使用S3 bucket instance,或者使用自定义标签过滤器重定向图像实例的url。
settings.py
S3_ROOT_PATH = "<define your S3 hosting path>"
teamplatetags/s3static
from settings import STATIC_URL, S3_ROOT_PATH
from django import template
register = template.Library()
@register.filter
def s3_static_thumb(image_instance=None):
return "{s3_root_path}{static_path}{image_url}".format(s3_root_path=S3_ROOT_PATH, static_path=STATIC_URL, image_url=getattr(image_instance, "url")) if image_instance and hasattr(image_instance, "url") else None
最后,在你的模板中使用它:
{% load static thumbnail s3static %}
{% with image|s3_static_thumb as im_url %}
{% thumbnail image "720x306" crop="center" %}
{% if im %}
<img src="{{ im_url }}" width="{{ image.width }}" height="{{ image.height }}" alt=""/>
{% else %}
<img src="{{ STATIC_URL }}img/V.png" sizes="50x50" alt=""/>
{% endif %}
{% endwith %}