harish1988
harish1988

Reputation: 114

How to pass three or multiple arguments to custom template tag filter django?

How to send there arguments in @register.filter(name='thumbnail') template tag. I am using image resize function have contain 2 args image object and size now i want to pass third argument folder_name but i can't able to find the solution its gives error Could not parse the remainder: below are function which is template tag file and template.

Template Tag function

@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

Template File I have tried 2 different type

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

If any one have solution please help me. Thanks

Upvotes: 2

Views: 5356

Answers (1)

ruddra
ruddra

Reputation: 51948

In django, template filter does not accept multiple arguments. So you can try like this:

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

    ...

usage:

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

Please check this SO answer for more details.

Upvotes: 5

Related Questions