如何将三个或多个参数传递给自定义模板标签过滤器django?

时间:2018-11-30 05:40:13

标签: django django-templates django-template-filters

如何在@register.filter(name='thumbnail')模板标记中向其中发送参数。我正在使用图像调整大小功能,其中包含2个args图像对象和大小,现在我想传递第三个参数folder_name,但是我找不到解决方案,它给出了错误无法解析其余部分:功能是模板标记文件和模板。

模板标签功能

@register.filter(name='thumbnail')
def thumbnail(file, size='200x200',folder_name='users_images'): 
    x, y = [int(x) for x in size.split('x')]
    # defining the filename and the miniature filename
    filehead, filetail = os.path.split(file.path)
    basename, format = os.path.splitext(filetail)
    miniature = basename + '_' + size + format

    #filename = file.path
    #print(filehead+'/users_images/'+filetail)
    if os.path.exists(filehead+'/'+folder_name+'/'+filetail):        
        filename = filehead+'/'+folder_name+'/'+filetail
        filehead = filehead+'/'+folder_name+'/'
    else:
        filename = file.path

    #print(filename)
    miniature_filename = os.path.join(filehead, miniature)
    filehead, filetail = os.path.split(file.url)
    miniature_url = filehead + '/' + miniature
    if os.path.exists(
        miniature_filename
            ) and os.path.getmtime(filename) > os.path.getmtime(
                miniature_filename
                ):
        os.unlink(miniature_filename)

    # if the image wasn't already resized, resize it
    if not os.path.exists(miniature_filename):
        image = Image.open(filename)
        new_image = image.resize([x, y], Image.ANTIALIAS)
        # image.thumbnail([x, y], Image.ANTIALIAS)
    try:
        # image.save(miniature_filename, image.format, quality=90, optimize=1)
        new_image.save(miniature_filename, image.format,
                       quality=95, optimize=1)
    except:
        return miniature_url

    return miniature_url

模板文件 我尝试了2种不同的类型

{{ contact_list.picture|thumbnail:'200x200' 'contacts'}}
{{ contact_list.picture|thumbnail:'200x200','contacts'}}

如果有人有解决方案,请帮助我。 谢谢

1 个答案:

答案 0 :(得分:2)

在Django中,模板过滤器does not accept multiple arguments。所以你可以这样尝试:

@register.filter(name='thumbnail')
def thumbnail(file, args):
    _params = args.split(',')
    if len(_params) == 1:
      size = _params[0]
      folder_name = "default_folder"
    elif len(_params) == 2:
       size = _params[0]
       folder_name = _params[1]
    else:
       raise Error

    x, y = [int(x) for x in size.split('x')]

    ...

用法:

{{ contact_list.picture|thumbnail:'200x200,contacts'}}

请检查此SO answer以获得更多详细信息。