首页IT科技multiple editions什么版本(Multiple arguments in Django template filters)

multiple editions什么版本(Multiple arguments in Django template filters)

时间2025-05-01 17:45:00分类IT科技浏览4256
导读:Multiple arguments in Django template filters...

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 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:

[u1, u2, u3]

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>

Doesnt look pretty, but works perfectly.

声明:本站所有文章            ,如无特殊说明或标注                  ,均为本站原创发布            。任何个人或组织      ,在未征得本站同意时            ,禁止复制            、盗用                  、采集      、发布本站内容到任何网站      、书籍等各类媒体平台                  。如若本站内容侵犯了原著者的合法权益                  ,可联系我们进行处理      。

创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!

展开全文READ MORE
整理磁盘碎片时需要注意哪些问题(硬盘维护:整理磁盘碎片) cprogram函数不正确(C Programming Notes)