python - 在 JINJA2 中连接列表

标签 python jinja2

如何在 jinja2 中连接两个列表变量?

例如

GRP1 = [1, 2, 3]
GRP2 = [4, 5, 6]

{# This works fine: #}
{% for M in GRP1 %}
    Value is {{M}}
{% endfor %}


{# But this does not: #}
{% for M in GRP1 + GRP2 %}
    Value is {{M}}
{% endfor %}

因此,我尝试使用 + 连接两个列表(就像在 Python 中那样),但事实证明它们不是列表,而是 python xrange 对象:

jijna2 error: unsupported operand type(s) for +: 'xrange' and 'xrange'

有没有办法让我在同一个 for 循环中迭代 GRP1 和 GRP2 的串联?

最佳答案

据我所知,您不能使用 native Jinja2 模板来做到这一点。您最好创建一个新的组合迭代器并将其传递给您的模板,例如:

from itertools import chain

x = xrange(3)
y = xrange(3, 7)
z = chain(x, y) # pass this to your template
for i in z:
    print i

根据评论,您可以明确地将可迭代对象转换为列表,并将它们连接起来:

{% for M in GRP1|list + GRP2|list %}

关于python - 在 JINJA2 中连接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15879983/

相关文章:

django - Jinja和Django无效的阻止标签: 'set' , expected 'endblock'

python - 使用带空格的 Jinja2 字符串作为 HTML 属性

python - 选择 DataFrame.set_index 中的所有列,除了一个

python - Python中的 "int(a[::-1])"是什么意思?

python - 根据条件替换来自不同文件的字符串

python - 使用 Python Pytables 加载 Matlab 稀疏矩阵

python - 如何创建 404 页面?

python - 如何在 5x5 矩阵中找到 (0,0) 和 (4,4) 之间的最短路径,每步给出一个水平或垂直平移

python - 如何在没有 JQuery 的情况下使 HTML 表格行可点击?

python - jinja2.exceptions.UndefinedError: 'response'未定义