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

查看:85
本文介绍了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 来指定通过管道传输的字符串?请各位巨蟒修士帮忙!

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天全站免登陆