Django子模板可以将新块创建为钩子吗

问题描述:

我有以下情况:

base.html:

base.html:

{% block content %}{% endblock %}

child.html:

child.html:

{% extends 'base.html' %}
{% block content %}
   <p>Overriding content</p>
{% endblock %}
{% block child_block %}{% endblock %}

child_of_child.html:

child_of_child.html:

{% extends 'child.html' %}
{% block child_block %}
   <p>Overriding child</p>
{% endblock %}

在child.html中创建一个新的块child_block并拥有child_of_child .html扩展child.html并覆盖此块将不起作用,直到我还将base_html中的child_block也包含为一个钩子为止。

Creating a new block child_block in child.html and having child_of_child.html extending child.html and overriding this block does not work until I also include child_block in base.html as a hook.

不可能创建新的模板块/与根模板分开?如果是这样,是否有办法解决而不必在base.html中包含所有可能的钩子?

Is it not possible to create new template blocks / hooks apart from within the root template? If so, is there a way around it without having to include every possible hook inside base.html?

问题是您的 child_block 块不在 base.html 中的任何地方,因为它在现有块之外。呈现模板时它将出现在哪里?

The problem is that your child_block block doesn't live anywhere in base.html, because it's outside of existing blocks. Where would it appear when the template is rendered? There's simply no place defined for it.

完全可以使用子模板在其他块中定义块,然后再由其他子填充。因此,例如:

It's perfectly OK for child templates to define blocks inside other blocks, which are then populated by further children. So, for example:

{% extends 'base.html' %}
{% block content %}
   <p>Overriding content</p>
   {% block child_block %}{% endblock %}
{% endblock %}

绝对可以,并且您的结果将是:

works absolutely fine, and your result will be:

<p>Overriding content</p>
<p>Overriding child</p>