python - 如何在模板中使用带有静态的简单缩略图?
问题描述
我想知道如何(如果可能的话)使用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模型(文档参考)的实例。但是您可以实现自己的过滤器,将 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 %}
推荐阅读
- python - 将十六进制格式转换为字符串
- css - 如何在 bootstap-vue 切换按钮中更改背景颜色
- android - 如何在 API 完成时暂停 Kotlin 中的执行
- angular - 如何使用 *ngFor 在 angular 8 中的特定字符之后从字符串中删除特定文本?
- performance - 如何通过多个匹配和增加 where 子句的数量来优化和改进 neo4j 密码查询
- android - 尝试运行命令“flutter run”时出错
- packet - 应用过滤器,使用 tcpdump 读取除 DNS 和 TCP 之外的所有流量
- matplotlib - 如何使轴对象具有与默认图形大小相同的大小?
- python - Python 打印 api 特定值
- object - 包含 9999 多个对象的图库页面