【问题标题】:Filter 2D list with template tag in Django在 Django 中使用模板标签过滤二维列表
【发布时间】:2019-01-14 03:34:52
【问题描述】:

我正在尝试编写一个模板标签来过滤二维列表。

这是我的模板标签:

from django import template

register = template.Library()

@register.filter
def index_two(seq, position1, position2):
    return seq[position1][position2]

这是我要传递给模板的列表:

summary = [[50, 0, 0], [50, 100, 100]]

我试图在摘要中引用第一个列表的第一个元素,如下所示:

{{summary|index_two:0 0}}

但是,我收到一个模板语法错误:index_two 需要 3 个参数,提供 2 个。

我尝试将我的模板标签调整为答案here,但我无法让它为我工作。

有什么建议吗?

谢谢

【问题讨论】:

  • 根据文档,模板过滤器最多可以带两个参数。但是您可以例如将两者包装在一个字符串中,从而传递这两个参数。

标签: django python-3.x templatetags


【解决方案1】:

一个 Django 模板过滤器最多接受两个参数(一个是通过“管道”(|)字符传递的,另一个是可选的额外参数,就像在 documentation [Django-doc] 中指定的一样:

自定义过滤器只是需要一两个的 Python 函数 论据:

  1. 变量的值(输入)——不一定是字符串。
  2. 参数的值 - 这可以是默认值,也可以完全省略

但是我们可以让组件更加可重用,从而每次都获取一个元素,比如:

from django import template

register = template.Library()

@register.filter
def index(seq, position):
    return seq[position]

那么我们可以这样写:

{{ summary|<b>index:0|index:0</b> }}

所以现在我们可以使用index 来获取列表的一个元素,并且通过链接,我们可以更深入地了解列表。因此,我们使函数更具可重用性。

这种技术有点类似于函数式编程中的currying,其中函数总是只接受一个参数。

或者,您可以使用某种可以解码的格式,例如包含逗号分隔值的字符串:

from django import template

register = template.Library()

@register.filter
def index_two(seq, positions):
    p1, p2 = map(int, positions.split(','))
    return seq[p1][p2]

然后像这样使用它:

{{ summary|<b>index_two:'0,0'</b> }}

但我个人觉得这不太优雅,而且可能会造成更多麻烦,因为它需要一个明确定义的格式,而且在某些极端情况下它总是可能失败。

【讨论】:

    【解决方案2】:

    这个答案的灵感来自 Willem Van Onsem 的评论:

    模板标签:

    from django import template
    
    register = template.Library()
    
    @register.filter
    def index(seq, pos):
        position1 = int(pos.split(" ")[0])
        position2 = int(pos.split(" ")[1])
    
    return seq[position1][position2]
    

    模板:

    {{summary|index:'0 0'}
    

    【讨论】:

    • 大声笑,我们同时进行了相同的编辑 :)
    猜你喜欢
    • 2020-02-16
    • 2013-03-16
    • 2016-07-06
    • 2022-01-22
    • 2014-03-20
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    • 2015-11-23
    相关资源
    最近更新 更多