浙江省高等学校教师教育理论培训

微信搜索“教师资格证岗前培训”小程序

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Multiple arguments in Django template filters | nme.pl/en

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 I describe 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 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.

posted on 2012-04-26 11:16  lexus  阅读(471)  评论(0编辑  收藏  举报