Multiple arguments in Django template filters | nme.pl/en
Multiple arguments in Django template filters
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 I describe solution that allows passing more arguments.
Lets say we have
key
and currentquery_string
in our template context. We loop in paginator and alter query_string current key value withpage
. 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 import QueryDict query_dict = QueryDict(query_string, mutable=True) query_dict[keys[0]] = keys[1] return query_dict.urlencode()inside pagination template, we use following code:
<a href="?{{ key|keys:page|alter_query:query_string }}">{{ page }}</a>Doesn't look pretty, but works perfectly.