在 Jinja2 中合并多个列表

Mr *_*tro 4 list nested-lists jinja2

有没有办法在 Jinja2 的列表中组合多个列表?

例如,如果我有:

[['foo', 'moo'],['py','jinga','template'],['example'],['stack','overflow']]
Run Code Online (Sandbox Code Playgroud)

我期望得到:

['foo', 'moo','py','jinga','template','example','stack','overflow']
Run Code Online (Sandbox Code Playgroud)

(我事先不知道列表中有多少个列表。)

我已经尝试使用join()但它不起作用,因为我得到一个字符串而不是字符串列表。

β.ε*_*.βε 6

从 Jinja 2.10 开始,您可以使用命名空间来满足此要求。

\n

例如:

\n
{%- set list_of_lists = [\n    [\'foo\', \'moo\'],\n    [\'py\',\'jinga\',\'template\'],\n    [\'example\'],\n    [\'stack\',\'overflow\']\n] -%}\n\n{%- set ns = namespace(flattened_list=[]) -%}\n{%- for list in list_of_lists -%}\n  {%- set ns.flattened_list = ns.flattened_list + list -%}\n{%- endfor -%}\n\n{{ ns.flattened_list\xc2\xa0}}\n
Run Code Online (Sandbox Code Playgroud)\n

这给出了预期的列表:

\n
{%- set list_of_lists = [\n    [\'foo\', \'moo\'],\n    [\'py\',\'jinga\',\'template\'],\n    [\'example\'],\n    [\'stack\',\'overflow\']\n] -%}\n\n{%- set ns = namespace(flattened_list=[]) -%}\n{%- for list in list_of_lists -%}\n  {%- set ns.flattened_list = ns.flattened_list + list -%}\n{%- endfor -%}\n\n{{ ns.flattened_list\xc2\xa0}}\n
Run Code Online (Sandbox Code Playgroud)\n
\n

在 Jinja 2.10 之前,如果您事先不知道子列表的数量,因为 Jinja 不允许在循环中赋值,您可以做的是join通过 来返回子列表map,然后split返回。

\n

这不是完美的方式,但它可以完成工作。

\n
{% set list_of_lists = [\n    [\'foo\', \'moo\'],\n    [\'py\',\'jinga\',\'template\'],\n    [\'example\'],\n    [\'stack\',\'overflow\']\n] %}\n{{ (list_of_lists | map(\'join\',\'|||\') | join(\'|||\')).split(\'|||\') }}\n
Run Code Online (Sandbox Code Playgroud)\n
\n

您可以使用+运算符来串联列表:

\n
[\'foo\', \'moo\', \'py\', \'jinga\', \'template\', \'example\', \'stack\', \'overflow\']\n
Run Code Online (Sandbox Code Playgroud)\n

给予

\n
{% set list_of_lists = [\n    [\'foo\', \'moo\'],\n    [\'py\',\'jinga\',\'template\'],\n    [\'example\'],\n    [\'stack\',\'overflow\']\n] %}\n{{ (list_of_lists | map(\'join\',\'|||\') | join(\'|||\')).split(\'|||\') }}\n
Run Code Online (Sandbox Code Playgroud)\n
\n

+将两个对象添加在一起。通常对象是数字,但如果两者都是字符串或列表,则可以通过这种方式连接它们。

\n
\n

来源: https: //jinja.palletsprojects.com/en/2.11.x/templates/#math

\n