Can Django child template create new block as hook

故事扮演 提交于 2019-12-08 06:58:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!