当我想打印行内块级元素而不将它们分开(例如渲染块的流体网格)时遇到了这个问题,但我想要一个看起来干净的标记。
jinja2-htmlcompress 去除 HTML 标签之间的空格,也去除 jinja 标签和变量之间的空格。这并不理想,因为它会迫使您使用诸如{{ ' ' }} 之类的变通方法或诸如  之类的硬编码html 实体。
coffin 的 spaceless 标签看起来是理想的解决方案,但它添加了依赖项 (django) 和许多不必要的功能。
如果你只想使用 Django 的 spaceless 标签,可以使用我从 coffin 改编的以下代码:
jinja_extensions.py
# -*- coding: utf-8 -*-
from jinja2 import nodes
from jinja2.ext import Extension
import re
class SpacelessExtension(Extension):
"""
Removes whitespace between HTML tags at compile time, including tab and newline characters.
It does not remove whitespace between jinja2 tags or variables. Neither does it remove whitespace between tags
and their text content.
Adapted from coffin:
https://github.com/coffin/coffin/blob/master/coffin/template/defaulttags.py
"""
tags = set(['spaceless'])
def parse(self, parser):
lineno = parser.stream.next().lineno
body = parser.parse_statements(['name:endspaceless'], drop_needle=True)
return nodes.CallBlock(
self.call_method('_strip_spaces', [], [], None, None),
[], [], body,
).set_lineno(lineno)
def _strip_spaces(self, caller=None):
return re.sub(r'>\s+<', '><', caller().strip())
无论您在哪里定义 jinja2 环境
extensions=['path.to.jinja_extensions.SpacelessExtension']
使用示例
<style>
*, *:before, *:after { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; }
.features {
text-align: center;
}
.features div {
display: inline-block;
text-align: left;
width: 25%;
padding: 20px;
}
/* A style to help us identify the blocks */
.features div:nth-child(odd) {
background: #f5f5f5;
}
@media only screen and (max-width: 319px) {
/* For small screens, display a single feature per line */
.features div {
width: 100%;
}
}
</style>
{% spaceless %} {# We remove whitespace between these inline-block tags without affecting the markup #}
<div class="features">
<div>
<h2>Feature 1</h2>
<p>Content</p>
</div>
<div>
<h2>Feature 2</h2>
<p>Content</p>
</div>
<div>
<h2>Feature 3</h2>
<p>Content</p>
</div>
<div>
<h2>Feature 4</h2>
<p>Content</p>
</div>
<div>
<h2>Feature 5</h2>
<p>Content, second line on desktop</p>
</div>
</div>
{% endspaceless %}
无空格的结果
没有空格的结果
(注意不可见的空格已经把第四块移到了下一行)