Search code examples
pythondjangojinja2easy-thumbnails

Using easy-thumbnails (or other 3rd party library) with jinja2 in Django


What is the process for using a third party filter like easy-thumbnails with Jinja2 in Django? Do I need to somehow register the filters I need to use? Specifically, I want to use the thumbnail_url filter that I used to use like:

<img src="{{ the_thing.image|thumbnail_url:'homepage_large' }}">

I tried to convert this to the Jijnja2 syntax like so:

{{ the_thing.image|thumbnail_url('homepage_large') }}

but get the following error:

django.template.base.TemplateSyntaxError: ("no filter named 'thumbnail_url'",)

Solution

  • You'll need to add the filter to your Jinja2 environment:

    def environment(**options):
        env = Environment(**options)
        env.globals.update(**{
            'static': staticfiles_storage.url,
            'url': reverse,
        })
    
        # add easy-thumbnails function as a Jinja2 filter
        from easy_thumbnails.templatetags.thumbnail import thumbnail_url
        env.filters.update(**{
            'thumbnail_url': thumbnail_url,
        })
    
        return env
    

    You should be aware that the template tags in easy-thumbnails are built for Django templates. However, in this very specific case, the thumbnail_url function just also happens to work with Jinja2 templates.

    A better implementation would be to write your own functions to wrap the functionality implemented in easy-thumbnails, and to use those functions as your Jinja2 filters instead.