flask模板应用-空白控制 --

模板应用实践

空白控制

在实际输出的HTML文件中,模板中的jinja2语句、表达式和注释会保留移除后的空行。

例如下面的代码:

{% set user.age = 23 %}
{% if urer.age > 10 %}
    <i>{{ user.name }} can play the game</i>
{% if user.name >20 %}
    <i>{{ user.name }}can paly the game only 10 minutes! </i>
{% endif %}

jinja2语句中的代码缩进并不是必须的,添加缩进可以增加可读性。

实际输出的HTML代码:
<i>{{ user.name }} can play the game</i>
 
<i>{{ user.name }}can paly the game only 10 minutes! </i>

如果想再渲染时自动去掉空行,可以在定界符内侧添加减号。比如{%-endfor%}会移除该语句前的空白,同理,在右边的定界符内侧添加减号将移除该语句后的空白:

{% set user.age = 23 -%}
{% if urer.age > 10 -%}
    <i>{{ user.name }} can play the game</i>
{% if user.name >20 -%}
    <i>{{ user.name }}can paly the game only 10 minutes! </i>
{%- endif %}

现在输出的HTML代码如下:

<i>{{ user.name }} can play the game</i>
<i>{{ user.name }}can paly the game only 10 minutes! </i>

除了在模板中使用减号来控制空白,也可以使用模板环境对象提供的trim_blocks和lstrip_blocks属性设置,前者用来删除jinja2语句后的第一个空行,后者则用来删除jinja2语句所在行之前的空格和制表符(tab):

app.jinja_env.trim_blocks = True

app.jinja_env.lstrip_blocks = True

trim_blocks中的block指的是使用{% … %}定界符的代码块,与模板继承中的块无关。

需要注意,宏内的空白行为不受trim_blocks和lstrip_blocks属性控制,我们需手动设置,例如:

{% macro qux(amount=1) %}
    {% if amount ==1 -%}
        I am qux.
    {% elif amount > 1 -%}
{% endmacro %}

事实上,我们没有必要严格控制HTML输出,因为多余的空白并不影响浏览器的解析
原文地址:https://www.cnblogs.com/xiaxiaoxu/p/10468038.html