Enrico Tuvera Jr
Enrico Tuvera Jr

Reputation: 2817

Template Inheritance in Django

I'm using Django 1.1, and I have this template, a base template, that all the other pages inherit from. It defines a bunch of things that are constant throughout pretty much all of the website, like this navbar:

        <div id="navbar">
        {% block navbar %}
            <a href="">Link 1</a>
            <a href="">Link 2</a>
            <a href="">Link 3</a>
            <a href="">Link 4</a>
            <a href="/admin/">Admin</a>
        {% endblock %}
    </div>

But Django's default behavior within child templates is to have the child completely override blocks in the parent template. I've got this page here that doesn't necessarily have to override the navbar block, just add a few more entries to it that'll be specific to that page, but right now the only way I can see that happening is if I were to copy the navbar block from the parent and then include it in the template + my additions. Is there any other way that can be done?

Upvotes: 2

Views: 987

Answers (4)

Carl Meyer
Carl Meyer

Reputation: 126581

You can define nested blocks, so you could also do something like this:

    <div id="navbar">
            {% block navbar %}
                    <a href="">Link 1</a>
                    <a href="">Link 2</a>
                    <a href="">Link 3</a>
                    <a href="">Link 4</a>
                    <a href="/admin/">Admin</a>
                    {% block navbar-extra %}{% endblock %}
            {% endblock %}
    </div>

Templates that need to override the entire navbar could do so, while other templates could just override the "navbar-extra" block. IMO this is a little cleaner than using {{ block.super }} in situations where you know in advance where you'll need the extensibility; YMMV.

Upvotes: 2

Daniel Roseman
Daniel Roseman

Reputation: 599610

As Alasdair noted, {{ block.super }} allows you to use the value from the parent.

However, if you're finding you always need to do this, you should consider whether your blocks are granular enough. You should be able to lay them out in such a way that each block only defines the content it needs.

Upvotes: 2

Alasdair
Alasdair

Reputation: 308849

Use {{ block.super }} in the child template to include the content from the parent block.

Upvotes: 8

Michal Čihař
Michal Čihař

Reputation: 10091

You don't have to define all blocks, so if you don't define navbar block in child page, it will use block content from parent.

Upvotes: 0

Related Questions