multiple editions什么版本(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版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!