从扩展模板覆盖`include`d模板中的块 [英] Overwriting a block within an `include`d template from an extended template

查看:127
本文介绍了从扩展模板覆盖`include`d模板中的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容:

base.html

<html>
    {% include 'header.html' %}
    <div>
    {% block content %}Default Content{% endblock %}
    </div>
</html>

header.html

<header>
     {% block logo %}Logo 1{% endblock %}
</header>

homepage.html

{% extend 'base.html' %}
{% block logo %}Logo 2{% endblock %}
{% block content %}Yap Yap Yap{% endblock %}

本质上这不行。当我呈现 homepage.html 时,我得到:

Essentially, this doesn't work. When I render the homepage.html I get:

<html>
    <header>Logo 1</header>
    <div>Yap Yap Yap</div>
</html>

但是如果我在 header.html into base.html (即,删除 include 一起)它可以正常工作。有人可以解释为什么会这样吗?

but If I move the code in header.html into base.html (i.e. get rid of the include altogether) it works ok. Can anyone explain why this is the case?

我有一种感觉,它与包含的模板在父母呈现后被渲染有什么关系?

I have a feeling it has something to do with the included templates getting rendered after their parents have been rendered?

推荐答案

从文档


include标签应被视为实现渲染此子模板并包含HTML,而不是解析此子模板并将其内容包含为父类的一部分。这意味着包含的模板之间没有共享状态 - 每个include都是完全独立的渲染过程。

The include tag should be considered as an implementation of "render this subtemplate and include the HTML", not as "parse this subtemplate and include its contents as if it were part of the parent". This means that there is no shared state between included templates -- each include is a completely independent rendering process.

所以子模板code> header.html )正在完全渲染并插入父模板( base.html ),这意味着没有概念的子模板块( homepage.html )覆盖

so the subtemplate (header.html) is getting fully rendered and inserted into the parent template (base.html), meaning there is no concept of the block for the child template (homepage.html) to overwrite

这篇关于从扩展模板覆盖`include`d模板中的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆