在使用Ansible渲染的Jinja模板中插入回车符。

huangapple go评论99阅读模式
英文:

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') }}

huangapple
  • 本文由 发表于 2023年7月17日 18:08:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76703406.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定