Python Jinja2 call to macro results in (undesirable) newline
<p>My JINJA2 template is like below.</p>

<pre><code>{% macro print_if_john(name) -%}
{% if name == 'John' -%}
  Hi John
{%- endif %}
{%- endmacro %}
Hello World!
{{print_if_john('Foo')}}
{{print_if_john('Foo2')}}
{{print_if_john('John')}}
</code></pre>

<p>The resulting output is</p>

<pre><code>Helloâ¢World!


Hiâ¢John
</code></pre>

<p>I don't want the 2 newlines between 'Hello World!' and 'Hi John'. It looks like when a call to macro results in no output from macro, JINJA is inserting a newline anyways.. Is there any way to avoid this? I've put minus in the call to macro itself but that didn't help.</p>

<p>Note that I tested this template and resulting code at <a href="http://jinja2test.tk/" rel="nofollow">http://jinja2test.tk/</a></p>

<p>The newlines come from the <code>{{print_if_john(...)}}</code> lines themselves, <em>not</em> the macro. </p>

<p>If you were to join those up or use <code>-</code> within those blocks, the newlines disappear:</p>

<pre><code>&gt;&gt;&gt; from jinja2 import Template
&gt;&gt;&gt; t = Template('''\
... {% macro print_if_john(name) -%}
... {% if name == 'John' -%}
...   Hi John
... {% endif %}
... {%- endmacro -%}
... Hello World!
... {{print_if_john('Foo')-}}
... {{print_if_john('Foo2')-}}
... {{print_if_john('John')-}}
... ''')
&gt;&gt;&gt; t.render()
u'Hello World!\nHi John\n'
&gt;&gt;&gt; print t.render()
Hello World!
Hi John
</code></pre>

<p>Note that you can still use newlines and other whitespace within the <code>{{...}}</code> blocks.</p>

<p>I removed the initial <code>-</code> from the <code>{% endif %}</code> block because when you remove the newlines from the <code>{{..}}</code> blocks, you want to <em>add one back in</em> when you actually do print the <code>Hi John</code> line. That way multiple <code>print_if_john('John')</code> calls will still get their line separators.</p>

<p>The full template, freed from the demo session:</p>

<pre class="lang-none prettyprint-override"><code>{% macro print_if_john(name) -%}
{% if name == 'John' -%}
  Hi John
{% endif %}
{%- endmacro -%}
Hello World!
{{print_if_john('Foo')-}}
{{print_if_john('Foo2')-}}
{{print_if_john('John')-}}
</code></pre>

python macros jinja2