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()但它不起作用,因为我得到一个字符串而不是字符串列表。
从 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}}\nRun 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}}\nRun Code Online (Sandbox Code Playgroud)\n在 Jinja 2.10 之前,如果您事先不知道子列表的数量,因为 Jinja 不允许在循环中赋值,您可以做的是join通过 来返回子列表map,然后split返回。
这不是完美的方式,但它可以完成工作。
\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(\'|||\') }}\nRun Code Online (Sandbox Code Playgroud)\n您可以使用+运算符来串联列表:
[\'foo\', \'moo\', \'py\', \'jinga\', \'template\', \'example\', \'stack\', \'overflow\']\nRun 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(\'|||\') }}\nRun Code Online (Sandbox Code Playgroud)\n\n\n\n
+将两个对象添加在一起。通常对象是数字,但如果两者都是字符串或列表,则可以通过这种方式连接它们。
来源: https: //jinja.palletsprojects.com/en/2.11.x/templates/#math
\n