1

给定 Ansible Jinja2 模板:

{% macro directive(name, value) %}
{% if value is defined %}
{{ name }}={{ value }}
{% endif %}
{% endmacro -%}

# {{ ansible_managed }}

[Unit]
{{ directive('Description', service.description) }}
{{ directive('Documentation', service.documentation) }}
{{ directive('Requires', service.requires) }}

service变量定义:

service:
  description: Test Template
  requires: multi-user.target

如何更改模板以消除结果输出中的额外换行符:

# Ansible managed

[Unit]
Description=Test Template


Requires=multi-user.target

所以它看起来像:

# Ansible managed

[Unit]
Description=Test Template
Requires=multi-user.target

?

4

1 回答 1

1

考虑以下:

{% 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) }}
于 2016-12-10T03:17:04.317 回答