首页 > 解决方案 > 如何在模板中使用带有静态的简单缩略图?

问题描述

我想知道如何(如果可能的话)使用easy-thumbnails包加载静态文件的缩略图。

我试过了:

<img src="{% thumbnail 'img/V.png' 50x0 %}" />
<img src="{% thumbnail static 'img/V.png' 50x50 %}" />
<img src="{% static thumbnail 'img/V.png' 50x50 %}" />

但没有任何效果。

标签: pythondjangoeasy-thumbnails

解决方案


easy-thumbnail包的注册标签过滤器没有以直接从静态目录渲染图像的方式实现。相反,它需要一个Image/FileField模型(文档参考)的实例。但是您可以实现自己的过滤器,将 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 %}

或者通过使用自定义标签过滤器来重定向图像实例的 url,如果您S3 bucket instance用于静态文件。

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 %}

推荐阅读