【问题标题】:DJango Template - Custom template tags pass 2 variablesDJango 模板 - 自定义模板标签传递 2 个变量
【发布时间】:2014-03-04 08:04:43
【问题描述】:

我需要这样做:

{% for team in association|get_teams_by_category_gender:category,gender %}

但是 django 不允许 2 个参数...我该怎么做?

基本上,我需要过滤器返回一个对象列表,以便循环遍历它,然后按类别和性别过滤团队。

谢谢, 阿拉

【问题讨论】:

    标签: django templates django-templates


    【解决方案1】:

    这里,

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

    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):
        if args is None:
            return False
        arg_list = [arg.strip() for arg in args.split(',')]
        return var in arg_list
    
    register.filter(is_in)
    

    How do I add multiple arguments to my custom template filter in a django template?

    【讨论】:

    • 您好,感谢您的回复。执行“类别,性别”的问题将采用字符串类别。但我希望它采用对象类别....
    • @AraSivaneswaran Django 只允许您的过滤器使用一个参数,因此您需要将性别值和类别值作为字符串发送,该字符串使用split(',') 处理您的模板标签方法。
    • 并编写自己的逻辑。
    • 谢谢,我明白了!
    猜你喜欢
    • 1970-01-01
    • 2015-03-16
    • 2021-02-15
    • 2011-10-12
    • 2021-09-04
    • 2012-09-27
    • 2019-07-31
    • 2015-06-22
    • 1970-01-01
    相关资源
    最近更新 更多