Renaming sorl-thumbnail images in templates

假装没事ソ 提交于 2019-12-13 00:57:28

问题


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



来源:https://stackoverflow.com/questions/18400199/renaming-sorl-thumbnail-images-in-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!