英文:
Insert carriage returns in Jinja template rendered with Ansible
问题
我正在为一个具有非常长行的CSV文件编写Ansible模板:
{{ hostvars[h]['myvar'][0]['firstvar'] | default('foo') }},{{ hostvars[h]['myvar'][0]['secondvar'] | default('bar') }},{{ hostvars[h]['myvar'][0]['thirdvar'] | default('baz') }}, {# ... #}
我想要在逗号之后为了可读性分割行,但这也会在模板输出中插入换行符,导致它断开。如何在行中插入换行符而不出现在输出中?
英文:
I am writing an Ansible template for a CSV file with very long lines:
{{ hostvars[h]['myvar'][0]['firstvar'] | default('foo') }},{{ hostvars[h]['myvar'][0]['secondvar'] | default('bar') }},{{ hostvars[h]['myvar'][0]['thirdvar'] | default('baz') }}, {# ... #}
I'd like to split the lines for readability (after the ,
), but this also insert carriage returns into the template output, breaking it.
How can carriage returns be inserted in the line without appearing in the output?
答案1
得分: 2
你可以在这种情况下使用Jinja的空白控制:
{{ hostvars[h]['myvar'][0]['firstvar'] | default('foo') }},
{{- hostvars[h]['myvar'][0]['secondvar'] | default('bar') }},
{{- hostvars[h]['myvar'][0]['thirdvar'] | default('baz') }}
或者你可以使用块可以跨多行包装而不会导致空白的事实:
{{
hostvars[h]['myvar'][0]['firstvar'] | default('foo')
}},{{
hostvars[h]['myvar'][0]['secondvar'] | default('bar')
}},{{
hostvars[h]['myvar'][0]['thirdvar'] | default('baz')
}}
顺便提一下:当访问字典属性时,使用点符号表示法也可以稍微简化语法:
{{ hostvars[h]['myvar'][0]['firstvar'] | default('foo') }}
也可以写成
{{ hostvars[h].myvar.0.firstvar | default('foo') }}
英文:
You can use Jinja's whitespace control for this use case:
{{ hostvars[h]['myvar'][0]['firstvar'] | default('foo') }},
{{- hostvars[h]['myvar'][0]['secondvar'] | default('bar') }},
{{- hostvars[h]['myvar'][0]['thirdvar'] | default('baz') }}
Or you can use the fact that a block can be wrapped on multiple lines without causing any blanks:
{{
hostvars[h]['myvar'][0]['firstvar'] | default('foo')
}},{{
hostvars[h]['myvar'][0]['secondvar'] | default('bar')
}},{{
hostvars[h]['myvar'][0]['thirdvar'] | default('baz')
}}
Side note: using the dot notation, when accessing attributes of a dictionary could also lighten a bit the syntax:
{{ hostvars[h]['myvar'][0]['firstvar'] | default('foo') }}
could also be written
{{ hostvars[h].myvar.0.firstvar | default('foo') }}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论