【问题标题】:Django - block tags in included templates don't work - Why?Django - 包含模板中的块标签不起作用 - 为什么?
【发布时间】:2012-07-07 17:23:43
【问题描述】:

这个问题有点像this one,除了一个小改动——

我在 parent.html 中有块标签,有些在调用模板中填写,有些在包含的模板中。包含的不起作用。例如:

#parent.html
<head>{% block head %}Parent head {% endblock %} </head>
<body> {% block body %} Parent body {% endblock %} 
</body>

#include.html

{%block body %} Child body {% endblock %}

#child.html
{% extends 'parent.html' %}

{% block head %}
Child head 
{% endblock %}

{% include 'include.html' %}

但这给出了输出: 儿童头 父体

想要的:

儿童头 孩子的身体

有什么解决方法吗?

【问题讨论】:

    标签: django include block


    【解决方案1】:

    这个:

    {% include 'include.html' %}
    

    不包含在任何块中,也不会被渲染,正如您在响应中看到的那样。

    以这种方式修改您的 child.html:

    #child.html
    {% extends 'parent.html' %}
    
    {% block head %}
    Child head 
    {% endblock %}
    
    {% block body %}
        {% include 'include.html' %}
    {% endblock %}
    

    如果你想在 child.html 和 include.html 中定义一些 html,那么你应该有:

    #child.html
    {% extends 'parent.html' %}
    
    ....
    
    {% block body %}
        {% include 'include.html' %}
        some child html...
    {% endblock %}
    

    在include.html中:

    {% block body %}
        {{ block.super }}
        some include html...
    {% endblock %}
    

    这将呈现:

    some child html
    some include html
    

    【讨论】:

    • 我在想有一个 footer.html 有一个 {% block footer %} 页脚 {%endblock %} 可以在任何模板中使用包含标记“插入”正在渲染 - 在某种程度上,免维护(无需提及每次进入哪个块)和多用途包含。猜猜用 Django 是不可能的。
    猜你喜欢
    • 2013-04-02
    • 1970-01-01
    • 2011-06-24
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    • 1970-01-01
    • 2011-04-28
    相关资源
    最近更新 更多