在模板中重命名sorl-thumbnail图像 [英] Renaming sorl-thumbnail images in templates

查看:122
本文介绍了在模板中重命名sorl-thumbnail图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 sorl-thumbnail ,通过 Django 模板中的缩略图模板标签,如下所示: / p>

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 %}

原始文件名包含与我相关的一些信息用户下载它们的情况。当我使用 sorl-thumbnail 调整图像大小时,调整大小的图像将获得一个新名称。

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.

有没有一种方法-thumbnail - 生成的图像以保留原始文件的名称(也许附加-thumb),或者使用模板中的代码重命名文件? (我想离开模型。)

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.)

推荐答案

是的,可以通过基于默认的方式创建自己的后端并重载 _get_thumbnail_filename 方法。

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

例如,像这样的

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']])

然后你必须激活这个新的后端您的项目 settings.py

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

THUMBNAIL_BACKEND = 'path.to.KeepNameThumbnailBackend'

我希望它有助于

这篇关于在模板中重命名sorl-thumbnail图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆