4

My JINJA2 template is like below.

{% 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')}}

The resulting output is

Hello•World!


Hi•John

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.

Note that I tested this template and resulting code at http://jinja2test.tk/

1 Answers1

5

The newlines come from the {{print_if_john(...)}} lines themselves, not the macro.

If you were to join those up or use - within those blocks, the newlines disappear:

>>> from jinja2 import Template
>>> 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')-}}
... ''')
>>> t.render()
u'Hello World!\nHi John\n'
>>> print t.render()
Hello World!
Hi John

Note that you can still use newlines and other whitespace within the {{...}} blocks.

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

The full template, freed from the demo session:

{% 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')-}}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343