【问题标题】:Django template tags filter with multiple arguments带有多个参数的 Django 模板标签过滤器
【发布时间】:2019-07-30 00:34:31
【问题描述】:

带有多个参数的 Django 模板标签过滤器

@register.filter
def customTag(value, first, second):
...
return result

模板

{{ valor|customTag:first|customTag:second }}

错误

customTag 需要 3 个参数,提供 2 个

【问题讨论】:

  • ......问题是......?
  • 错误 customTag 需要 3 个参数,提供 2 个

标签: python django python-3.x python-2.7 django-templates


【解决方案1】:

我认为只传递整个 customTag 而不是参数可能会解决问题。也许还有其他可能的解决方案。

@register.filter("filter_of_custom_tag")
def customTag(custom_tag_instance):
... 
return result

在你的模板中

{{ customTag|filter_of_custom_tag}}

【讨论】:

  • 我需要更多参数
  • @marcelo.delta 我发现了一篇关于类似问题link 的stackoverflow 帖子。你能检查一下,这能解决你的问题吗?
【解决方案2】:

您不能将多个参数传递给过滤器 (reference)。相反,您可以这样做:

@register.filter
def customTag(value, args):
   first, second = args.split(',')
   ...
   return value

{{ valor|customTag:"first,second"}}  // pass comma separated arguments in string

【讨论】:

    【解决方案3】:

    我也有这个疑问。 我在 django 模板中使用 {% with as %} 得到了很好的结果,但我需要创建两个过滤器模板标签:

    模板标签:

    @register.filter
    def customTag(value, first):
    ...
    return result1
    
    @register.filter
    def customTag2(first, second):
    ...
    return result2
    

    模板html:

    {% with value|custom_tag:first as r1%}
        {% with r1|custom_tag2:second as r2 %}
            use your r2 value: {{ r2 }}
        {% endwith %}
    {% endwith %}
    

    【讨论】:

      猜你喜欢
      • 2010-10-28
      • 2011-10-03
      • 1970-01-01
      • 2013-03-16
      • 2020-02-16
      • 1970-01-01
      • 2020-05-02
      • 1970-01-01
      • 2011-09-30
      相关资源
      最近更新 更多