Search code examples
djangoimagetemplatesthumbnailssorl-thumbnail

Django: sorl-thumbnail and easy-thumbnail in same project


I'm working on and project that uses two separate modular Django apps. However, one app requires easy-thumbnails and the other requires sorl-thumbnails. Unfortunately, the two thumbnail libraries make use of the template tag syntax {% load thumbnail %}, so they clash and break when a template using them tries to render.

Are there any approaches to solve this type of clash? (For example, a template option does to the effect of {% load thumbnail as easy_thumbnail %}). Am I going to have to fork one of the apps and replace one of the thumbnail libraries with another? If so, which should I choose to go with?

Thank you for considering my question, Joe


Solution

  • In Django 1.9, you can use the libraries option of DjangoTemplates to include a tag library under a specified name. In the example below, the thumbnail library from sorl.thumbnail is included under the name sorl_thumbnail.

    Note: the templatetag itself is not changed within the template... ie. remains thumbnail

    Usage:

    settings.py

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, "foo", "templates")],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
                'libraries': {
                    'sorl_thumbnail': 'sorl.thumbnail.templatetags.thumbnail',
                },
            },
        },
    ]
    

    your_template.html

    {% load sorl_thumbnail %}
    {% thumbnail mymodel.image "640x480" crop="center" as im %}
        <img src="{{ im.url }}" width="{{im.width}}" height="{{im.height}}"/>
    {% endthumbnail %}