问题
I have the following scenario:
base.html:
{% block content %}{% endblock %}
child.html:
{% extends 'base.html' %}
{% block content %}
<p>Overriding content</p>
{% endblock %}
{% block child_block %}{% endblock %}
child_of_child.html:
{% extends 'child.html' %}
{% block child_block %}
<p>Overriding child</p>
{% endblock %}
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.
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?
回答1:
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>
来源:https://stackoverflow.com/questions/12563828/can-django-child-template-create-new-block-as-hook