Multiple arguments in Django template filters

Author: nme · Tuesday, 5 July, 2011 · No comments ·

By default, it is not currently possible to pass multiple arguments to Django template filter — documentation states: "Custom filters are just Python functions that take one or two arguments".

Here Idescribe solution that allows passing more arguments.

Lets say we have key and current query_string in our template context. We loop in paginator and alter query_string current key value with page. The key is to group arguments in an array. We use following custom filter:

@register.filter
def keys (first,second):
  if isinstance(first,list):
    return first+[second]
  else:
    return[first,second]

following filter allows us to:

{{"1"|keys:"2"|keys:"3"}}

which will return in our template:

[u'1', u'2', u'3']

Returning to described query_string altering problem — we use alter_query filter:

@register.filter
def alter_query (keys, query_string):
  from django.http importQueryDict
  query_dict =QueryDict(query_string,mutable=True)
  query_dict[keys[0]]= keys[1]
  return query_dict.urlencode()

inside pagination template, we use following code:

<ahref="?{{ key|keys:page|alter_query:query_string }}">{{ page }}</a>

Doesn't look pretty, but works perfectly.

发表回复