views:

116

answers:

4

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?

A: 

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.

Michal Čihař
+6  A: 

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

Alasdair
+2  A: 

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.

Daniel Roseman
+2  A: 

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.

Carl Meyer