Jinja2:格式+加入列表中的项目 [英] Jinja2: format + join the items of a list

查看:220
本文介绍了Jinja2:格式+加入列表中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

play_hosts是要播放的所有计算机的列表.我想接受这些并使用类似format()的东西来重写它们,例如rabbitmq@%s,然后将它们与类似join()的东西连接在一起.所以:

play_hosts is a list of all machines for a play. I want to take these and use something like format() to rewrite them like rabbitmq@%s and then join them together with something like join(). So:

{{ play_hosts|format(???)|join(', ') }}

所有格式示例都使用管道,其中输入是格式字符串而不是列表.有没有办法使用这些(或其他方式)来完成我想要的?输出应类似于:

All the examples of format use piping where the input is the format string and not a list. Is there a way to use these (or something else) to accomplish what I want? The output should looks something like:

['rabbitmq@server1', 'rabbitmq@server2', rabbitmq@server3', ...]

jinja2文档描述了这样的格式:

The jinja2 doc describes format like this:

format(value, *args, **kwargs)

在对象上应用python字符串格式:

Apply python string formatting on an object:

{{ "%s - %s"|format("Hello?", "Foo!") }}
-> Hello? - Foo!

因此,它提供了三种输入,但在示例中未描述这些输入,该示例显示了管道中的一种输入,另外两种通过args传入.是否有关键字arg指定要传递的字符串?请帮忙,python僧侣!

So it gives three kinds of input but doesn't describe those inputs in the example, which shows one in the pipe and the other two passed in via args. Is there a keyword arg to specify the string that's piped? Please help, python monks!

推荐答案

在Ansible中,您可以使用regex_replace过滤器:

In ansible you can use regex_replace filter:

{{ play_hosts | map('regex_replace', '^(.*)$', 'rabbitmq@\\1') | list}

这篇关于Jinja2:格式+加入列表中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆