Jinja2模板设计文档—空格控制

In the default configuration:

在默认配置中:

  • a single trailing newline is stripped if present
  • 如果存在尾随换行符的单独空格,将被清除
  • other whitespace (spaces, tabs, newlines etc.) is returned unchanged
  • 其它空格(空格、tab换行符等)将原样返回

If an application configures Jinja to trim_blocks, the first newline after a template tag is removed automatically (like in PHP). The lstrip_blocks option can also be set to strip tabs and spaces from the beginning of a line to the start of a block. (Nothing will be stripped if there are other characters before the start of the block.)

如果应用配置为trim_blocks,模板标签后的第一个换行符将被自动移除(类似PHP)。也可以设置lstrip_blocks选项,这将移除块开始的一行之前的tab或者空格。(如果块开始有其它字符,则不会移除任何东西)

With both trim_blocks and lstrip_blocks enabled, you can put block tags on their own lines, and the entire block line will be removed when rendered, preserving the whitespace of the contents. For example, without the trim_blocks and lstrip_blocks options, this template:

如果同时启用trim_blockslstrip_blocks。你可以将块标签放在单独的一行,而且整行将在渲染时被移除,保留内容中的空白。例如没有trim_blockslstrip_blocks选项,本模板将如下:

<div>
    {% if True %}
        yay
    {% endif %}
</div>

gets rendered with blank lines inside the div:

获得渲染结果在div标签中有空行:

<div>

        yay

</div>

But with both trim_blocks and lbstrip_locks enabled, the template block lines are removed and other whitespace is preserved:

但是如果选项trim_blockslbstrip_locks启用的话,模板块行将被移除,而其它空白将被保留:

<div>
        yay
</div>

You can manually disable the lstrip_blocks behavior by putting a plus sign (+) at the start of a block:

您可以通过在块的起始位置添加一个加号(+)手动禁用lstrip_blocks行为:

<div>
        {%+ if something %}yay{% endif %}
</div>

You can also strip whitespace in templates by hand. If you add a minus sign (-) to the start or end of a block (e.g. a For tag), a comment, or a variable expression, the whitespaces before or after that block will be removed:

您也可以手动清除模块中的空白。如果您在块(例如For标签)、注释或者变量表达式的开始或者结尾添加一个减号(-),该块的前面或者后面的空白将被移除:

{% for item in seq -%}
    {{ item }}
{%- endfor %}

This will yield all elements without whitespace between them. If seq was a list of numbers from 1 to 9, the output would be 123456789.

该模板将会生成所有元素,并且元素之间没有空白。如果变量seq 是一个从19的数字列表,那么输出结果将是123456789

If Line Statements are enabled, they strip leading whitespace automatically up to the beginning of the line.

如果启用了行语句,这将导致清理前面的空白直到行首。

By default, Jinja2 also removes trailing newlines. To keep single trailing newlines, configure Jinja to keep_trailing_newline.

默认情况下,Jinja2会移除尾换行符。如果想保持单独的尾换行符,需要启用keep_trailing_newline选项。

Note

You must not add whitespace between the tag and the minus sign.

在标签和减号之前不要添加空白。

valid:

{%- if foo -%}...{% endif %}

invalid:

{% - if foo - %}...{% endif %}
如果引用本站的原创文章,请注明原文链接:,本站保留追究责任的权利!

发表评论