Search code examples
pythondjangoeasy-thumbnails

How to use easy-thumbnails with static in template?


I wonder how (if it is possible) load thumbnail for static files with easy-thumbnails package.

I tried:

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

but nothing works.


Solution

  • The registered tag filters for easy-thumbnail package are not implemented in a way to render images from the static directory directly. Rather it expects an instance of Image/FileField model (Doc Reference). But you can implement your own filter, redirect the url to static directory and use it based on your needs.

    Here, you can adopt one of the following strategies as well.

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

    or

    {% load static thumbnail %}
    {% thumbnail object.image|default:'{{ STATIC_URL }}img/V.png' 50x50 %}
    

    or by using a custom tag filter to redirect the url of the image instance, if you use S3 bucket instance for static files.

    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
    

    finally, use that in your template:

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