Nested django templates

有些话、适合烂在心里 提交于 2019-12-03 03:05:52

the extends template tag can take a variable argument.

so:

base.html
    {% block content %}
        <p>BASE</p>
    {% endblock %}

parent.html
    {% extends "base.html" %}

    {% block content %}
        {{ block.super }}
        <p>PARENT</p>
    {% endblock %}

foo.html
    {% extends ext_templ %}

    {% block content %}
        {{ block.super }}
        <p>FOO</p>
    {% endblock %}

using base:

return render_to_response('foo.html', {'ext_templ':'base.html'})

gives you:

<p>BASE</p>
<p>FOO</p>

using parent:

return render_to_response('foo.html', {'ext_templ':'parent.html'})

gives you:

<p>BASE</p>
<p>PARENT</p>
<p>FOO</p>

edit:

one way around this problem to get nested blocks is:

base.html
    {% block content %}
        {% block top %}
            <p>BASE START</p>
        {% endblock %}

        {% block bot %}
            <p>BASE END</p>
        {% endblock %}
    {% endblock %}


parent.html
    {% extends "base.html" %}

    {% block top %}
        {{ block.super }}
        <p>PARENT</p>
    {% endblock %}

    {% block bot %}
        <p>PARENT</p>
        {{ block.super }}
    {% endblock %}

foo.html
    {% extends ext_templ %}

    {% block top %}
        {{ block.super }}
        <p>FOO</p>
    {% endblock %}

    {% block bot %}
        <p>FOO END</p>
        {{ block.super }}
    {% endblock %}

The other method that i can think of is to wrap the blocks with an {% if ext_templ == 'parent.html' %} tag but that doesn't seem very dry. I'm curious to see other peoples response to nested blocks as well.

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