Renaming sorl-thumbnail images in templates

2019-08-10 22:45发布

问题:

I am using sorl-thumbnail via the thumbnail template tag in my Django templates, as follows:

{% thumbnail foo.imgA "1600x1200" as im %}
<a href='{{ im.url }}' title='{{ foo.imgA.url }}'>
{% endthumbnail %}

The original file name contains some information that is relevant to my users in case they download it. When I resize the image using sorl-thumbnail, the resized image gets a new name.

Is there a way for the sorl-thumbnail-generated image to keep the name of the original file (perhaps appending "-thumb"), or to rename the file using code in the template? (I would like to leave the model alone.)

回答1:

Yes it is possible by creating your own backend based on the default one and overload the _get_thumbnail_filename method.

For example, something like this

from sorl.thumbnail.base import ThumbnailBackend, EXTENSIONS

from sorl.thumbnail.conf import settings
from sorl.thumbnail.helpers import tokey, serialize
import os.path

class KeepNameThumbnailBackend(ThumbnailBackend):

    def _get_thumbnail_filename(self, source, geometry_string, options):
        """
        Computes the destination filename.
        """
        key = tokey(source.key, geometry_string, serialize(options))

        filename, _ext = os.path.splitext(os.path.basename(source.name))

        path = '%s/%s' % (key, filename)
        return '%s%s.%s' % (settings.THUMBNAIL_PREFIX, path, EXTENSIONS[options['format']])

Then you must activate this new backend in your project settings.py

THUMBNAIL_BACKEND = 'path.to.KeepNameThumbnailBackend'

I hope it helps