如何在django模板中为自定义模板过滤器添加多个参数? [英] How do I add multiple arguments to my custom template filter in a django template?

查看:757
本文介绍了如何在django模板中为自定义模板过滤器添加多个参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的自定义过滤器:



 从django导入模板

register = template.Library

@ register.filter
def replace(value,cherche,remplacement):
return value.replace(cherche,remplacement)



这里是我尝试在我的模板文件中使用它导致错误的方式:



  {{attr.name | replace:_,}} 
{{attr.name | replace:_}}
{{attr.name | replace:_:}}
{{attr.name | replace:cherche ='_',remplacement =''}}

我研究了 django的文档书籍,但只有使用单个参数发现的例子...甚至是可能的?

解决方案

这是可能而且相当简单的。 >

Django只允许你的过滤器的一个参数,但是没有理由你不能把所有的参数放在一个字符串中,使用逗号分隔它们。



所以对于例如,如果您想要一个过滤器,检查变量X是否在列表[1,2,3,4]中,您将需要一个如下所示的模板过滤器:

  {%if X | is_in:1,2,3,4%} 

现在我们可以像这样创建你的模板:

  from django.template import Library 

register = Library()

def is_in(var,args):
如果args为None:
return False
arg_list = [arg.strip ()for argssplit(',')]
return var in arg_list

register.filter(is_in)

创建arg_list的行是一个生成器表达式,它将args字符串分割在所有逗号上并调用.strip()以删除任何前导和尾随空格。



如果,例如,第三个参数是一个int然后只是做:

  arg_list [2] = int(arg_list [2])

或者如果所有这些都是ints:

  arg_list = [arg(arg)for args argssplit(',')] 


$编辑:现在通过使用键,值对作为参数来专门回答你的问题,你可以使用Django用来解析URL中的查询字符串,这样也可以正确处理字符编码的好处根据您的settings.py。



所以,与查询字符串一样,每个参数都用'&'分隔:$ / $ b

  {{attr.name | replace:cherche = _& remplacement =}} 

然后,您的替换函数现在将如下所示:

 从django导入模板
from django.http import QueryDict

register = template.Library()

@ register.filter
def replace(value,args):
qs = QueryDict(args)
如果qs.has_key('cherche')和qs.has_key('remplacement'):
return value.replace(qs ['cherche'],qs ['remplacement '])
else:
返回值

你可以加快一些有可能做一些不正确的替换:

  qs = QueryDict(args)
return value.replace(qs。 get('cherche',''),qs.get('remplacement',''))


Here's my custom filter:

from django import template

register = template.Library()

@register.filter
def replace(value, cherche, remplacement):
    return value.replace(cherche, remplacement)

and here are the ways I tried using it in my template file that resulted in an error:

{{ attr.name|replace:"_"," " }}
{{ attr.name|replace:"_" " " }}
{{ attr.name|replace:"_":" " }}
{{ attr.name|replace:"cherche='_', remplacement=' '" }}

I looked into django's docs and book but only found example using a single argument... is it even possible?

解决方案

It is possible and fairly simple.

Django only allows one argument to your filter, but there's no reason you can't put all your arguments into a single string using a comma to separate them.

So for example, if you want a filter that checks if variable X is in the list [1,2,3,4] you will want a template filter that looks like this:

{% if X|is_in:"1,2,3,4" %}

Now we can create your templatetag like this:

from django.template import Library

register = Library()

def is_in(var, args):
    if args is None:
        return False
    arg_list = [arg.strip() for arg in args.split(',')]
    return var in arg_list

register.filter(is_in)

The line that creates arg_list is a generator expression that splits the args string on all the commas and calls .strip() to remove any leading and trailing spaces.

If, for example, the 3rd argument is an int then just do:

arg_list[2] = int(arg_list[2])

Or if all of them are ints do:

arg_list = [int(arg) for arg in args.split(',')]

EDIT: now to specifically answer your question by using key,value pairs as parameters, you can use the same class Django uses to parse query strings out of URL's, which then also has the benefit of handling character encoding properly according to your settings.py.

So, as with query strings, each parameter is separated by '&':

{{ attr.name|replace:"cherche=_&remplacement= " }}

Then your replace function will now look like this:

from django import template
from django.http import QueryDict

register = template.Library()

@register.filter
def replace(value, args):
    qs = QueryDict(args)
    if qs.has_key('cherche') and qs.has_key('remplacement'):
        return value.replace(qs['cherche'], qs['remplacement'])
    else:
        return value

You could speed this up some at the risk of doing some incorrect replacements:

qs = QueryDict(args)
return value.replace(qs.get('cherche',''), qs.get('remplacement',''))

这篇关于如何在django模板中为自定义模板过滤器添加多个参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆