1

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'",)
Chris
  • 321
  • 3
  • 15

1 Answers1

2

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.

Derek Kwok
  • 12,768
  • 6
  • 38
  • 58
  • Is this how all third party tools will need to be integrated, or should we expect that they will likely inject themselves into the environment by some other means so we don't need to? – Chris Feb 26 '16 at 13:29
  • For Jinja2, you should expect to add everything to the environment yourself. That being said, I've found Jinja2 to be significantly more powerful than Django templates, and worth the extra effort for using. – Derek Kwok Feb 26 '16 at 17:14