Python Jinja2,使用带格式过滤器的地图,诀窍是什么?

Python Jinja2,使用带格式过滤器的地图,诀窍是什么?,python,templates,jinja2,Python,Templates,Jinja2,金甲2的新成员,我是地图功能的粉丝。因此,我打算使用MapFilter来格式化python列表。我阅读了Jinja2文档,其中映射过滤器可用于“在对象序列上应用过滤器”。但在Jinja2模板中使用map filter时,我没有找到一种明确的方法来传递参数到format filter 例如: python数据: colors = [ 'blue', 'red', 'green'] Jinja2模板(只需将python列表重新格式化为scheme样式) 想要的结果是colors=(列出“蓝色”“红

金甲2的新成员,我是地图功能的粉丝。因此,我打算使用MapFilter来格式化python列表。我阅读了Jinja2文档,其中映射过滤器可用于“在对象序列上应用过滤器”。但在Jinja2模板中使用map filter时,我没有找到一种明确的方法来传递参数到format filter

例如: python数据:

colors = [ 'blue', 'red', 'green']
Jinja2模板(只需将python列表重新格式化为scheme样式) 想要的结果是
colors=(列出“蓝色”“红色”“绿色”)

因此,我从下面的模板行开始,但它不明显地放置格式参数“%s”,map的第一个参数只是过滤器名称

colors=(list {{ colors | map('format') | join(" ")}})
我读了一些关于你们的解决办法

  • 使用ansible filter regexp replace执行此操作
  • Jinja2模板中结构的其他用途
{%for colors%}{{color}}{%endfor%}

但我只需要知道我是否错过了一些与地图和格式过滤器相关的东西

提前谢谢你的回答 问候


作为参考,我使用Python3.6.3和Jinja2 3.0.1

它不回答如何使用
map
,但我不会使用
map
连接中使用
'
,并将字符串放入

结果:

'colors=(list "blue" "red" "green")'

编辑:

如果我必须使用
map
,那么我会在发送到模板之前使用它

import jinja2

e = jinja2.Environment()

colors = [ 'blue', 'red', 'green']

#colors = list(map('"{}"'.format, colors))
#print(colors)

colors = map('"{}"'.format, colors)

t = e.from_string('colors=(list {{ colors | join(" ")}})')
result = t.render({'colors': colors})
print(result)
即使是在
jinja2
中的文档也说明了这一点

In most cases it should be more convenient and efficient to use   
the % operator or str.format().

我将使用
map
在将数据发送到
Jinja
之前,您可以在
join('''')
中使用
,如
列表“{colors | join('''')}”
In most cases it should be more convenient and efficient to use   
the % operator or str.format().