15

在扩展/包含模板时,我很难让 Django 的模板引擎正确缩进

这些文件:

index.html

<html>
    <body>
        <div id="hello">
            {% block bar %}
            {% endblock %}

            {% include 'baz.html'%}
        </div>
    </body>
</html>

bar.html

{% extends 'foo.html' %}

{% block bar %}
<p>bar</p>
{% endblock %}

baz.html

<p>baz</p>

将呈现为

<html>
    <body>
        <div id="hello">
<p>bar</p>
<p>baz</p>
        </div>
    </body>
</html>

我该如何修复它,使其呈现为

<html>
    <body>
        <div id="hello">
            <p>bar</p>
            <p>baz</p>
        </div>
    </body>
</html>

手动输入选项卡不是一种选择。如果这很重要,我正在使用软制表符(4 个空格)。

4

4 回答 4

7

Django 模板继承不会自动插入缩进。要实现您希望的缩进,您需要将其包含在bar.html

{% extends 'foo.html' %}

{% block bar %}
            <p>bar</p>
{% endblock %}
于 2013-01-04T11:49:13.907 回答
4

你应该解释一下你的缩进需要的目的。

缩进在调试步骤中非常有用,但缩进与优化不兼容,因为它存在无空间过滤器。

您可以编写自己的片段:

@register.tag
def myinden(parser, token):
    args = token.contents.split()
    n = args[1]
    nodelist = parser.parse(('endmyinden',))
    parser.delete_first_token()
    return MyIndenNode(nodelist, n)

class MyIndenNode(Node, n):
    def __init__(self, nodelist, n):
        self.nodelist = nodelist
        self.n = n

    def render(self, context):
        import re
        regex = re.compile("^", re.M)
        return re.sub(regex, "\t"*int(self.n),
                      self.nodelist.render(context).strip())

用法:

index.html
{% include 'baz.html' with indentation="8" %}

baz.html
{{ myindent:myindentation }}
...

注意,未经测试。另外,我建议您将代码段修改为仅在调试模式下工作:

于 2013-01-04T12:26:59.863 回答
1

You can override the NodeList's render method as I've done. See my question with working code:

Proper indentation in Django templates (without monkey-patching)?

于 2013-08-19T09:34:12.490 回答
1

上面提到的另一个选择是使用 Beautiful Soup 中间件。

这是一个教程。请注意,人们称此中间件为“非常”并建议缓存输出页面。

于 2014-11-22T21:00:44.053 回答