Jinja2对宏的调用导致

Jinja2对宏的调用导致

本文介绍了Python Jinja2对宏的调用导致(不需要的)换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的JINJA2模板如下.

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

结果输出是

Hello•World!


Hi•John

我不希望'Hello World!'之间有2条换行符.和嗨约翰".看起来当对宏的调用导致没有宏输出时,JINJA仍在插入换行符.是否有任何方法可以避免这种情况?我在宏本身的调用中加上了减号,但这无济于事.

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.

请注意,我在 http://jinja2test.tk/

推荐答案

换行符来自{{print_if_john(...)}}行本身,而不是宏.

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.

我从{% endif %}块中删除了初始的-,因为当您从{{..}}块中删除换行符时,您想在实际打印Hi John行.这样,多次print_if_john('John')调用仍将获得其行分隔符.

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

这篇关于Python Jinja2对宏的调用导致(不需要的)换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 11:29