2016-12-09 4 views
1

Данный шаблон анзибль Jinja2:Как удалить лишние пробелы между вызовами макросов в шаблонах 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 

?

ответ

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 

Даже если документация на whitespace control государств «одного завершающего символа новой строки удаляется, если присутствует», это не относится к переменной подстановка, поэтому, хотя результат макроса содержит символ новой строки в конце, эта новая строка не будет удалена.

Так же, как он не лишен, если вы определяете:

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) }} 
+0

Почему каждый макрос ссылка генерировать дополнительное пространство? –

+0

Да, я имел в виду «дополнительные строки» или новые строки. Я предполагаю, что я ошибочно ожидал, что Jinga2 автоматически удалит конечную новую строку из каждой ссылки на макросы, подобно тому, что она делает для каждого оператора '{%%}'. –

+0

Обратите внимание, что я добавил черту к '{% end macro -%}', чтобы исключить пробел между определением макроса и '# {{ansible_managed}}'. –