[英]Does Easy-Thumbnails use a “box” parameter in order to crop an image?
[英]How to use easy-thumbnails with static in template?
我想知道如何(如果可能)使用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 %}" />
但沒有任何效果。
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 %}
或者通過使用自定義標簽過濾器來重定向圖像實例的 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 %}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.