考虑以下:
{% macro directive(name, value) %}
{% if value is defined %}
{{ name }}={{ value }} # a newline hardcoded in macro follows
{% endif %}
{% endmacro -%}
# {{ ansible_managed }}
[Unit 1]
{{ directive('Description', service.description) }}# 1st hardcoded newline follows
{{ directive('Documentation', service.documentation) }}# 2nd hardcoded newline follows
{{ directive('Requires', service.requires) }}# 3rd hardcoded newline follows
它产生:
# Ansible managed
[Unit 1]
Description=Test Template # a newline hardcoded in macro follows
# 1st hardcoded newline follows
# 2nd hardcoded newline follows
Requires=multi-user.target # a newline hardcoded in macro follows
# 3rd hardcoded newline follows
即使有关空白控制的文档指出“如果存在单个尾随换行符,则剥离”,它不适用于变量替换,因此即使宏的结果在末尾包含换行符,这个特定的换行符也不会被剥离。
就像如果您定义它不会被剥离:
variable_with_newline: "value\n"
并运行一个模板:
start-{{ variable_with_newline }}-end
它产生:
start-value
-end
要修复模板,请删除硬编码的换行符:
[Unit]
{{ directive('Description', service.description) }}{{ directive('Documentation', service.documentation) }}{{ directive('Requires', service.requires) }}
或添加显式空格剥离:
[Unit]
{{ directive('Description', service.description) }}
{{- directive('Documentation', service.documentation) }}
{{- directive('Requires', service.requires) }}
或者
[Unit]
{{ directive('Description', service.description) -}}
{{ directive('Documentation', service.documentation) -}}
{{ directive('Requires', service.requires) }}