Python Jinja2 call to macro results in (undesirable) newline

依然范特西╮ 提交于 2019-12-13 16:12:54

问题


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:


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


来源:https://stackoverflow.com/questions/39626767/python-jinja2-call-to-macro-results-in-undesirable-newline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!