如何消除Ansible Jinja2模板中宏调用之间的额外空白?

时间:2016-12-09 22:54:47

标签: macros ansible jinja2 ansible-template

给出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 个答案:

答案 0 :(得分:1)

请考虑以下事项:

# 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"

即使whitespace control上的文档“单个尾随换行符被删除(如果存在”),它也不适用于变量替换,因此即使宏的结果包含换行符最后的字符,这个特殊的换行不会被删除。

如果您定义:

,就像它没有被剥离一样
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) }}

<?php
while($row = mysql_fetch_assoc($result)) {
    echo "
    <tr onclick=\"window.location.replace='http://example.com';\" style='cursor:pointer;'>
        <td>".$row["name"]."</td>
        <td align='center'>".$row["type"]."</td>
        <td align='center'>".$row["price"]."</td>
        <td align='center'>".$row["available"]."</td>
    </tr>";
}
?>