[Fixed]-Combining multiple Django templates in a single request

36👍

You can use django’s extends tag. Say you had a header and footer. You could make a template, called, say, foo.django:

<h1>My HTML Header</h1>
<!-- an so on -->

{% block content %}
{% endblock %}

<!-- html footer -->

Then, you can make another template, say, bar.django:

{% extends "foo.django" %}

{% block content %}
This overrides the content block in foo.django.
{% endblock %}

…which will then render:

<h1>My HTML Header</h1>
<!-- an so on -->

This overrides the content block in foo.django.

<!-- html footer -->

There’s good instructions on django templates at http://www.djangobook.com/en/1.0/chapter04/.

👤kris

13👍

The {% extends %} and {% include %} methods are good for page elements which don’t need extra information in the context.

As soon as you need to insert more stuff into the context from the database, template tags come handy. As an example, the contrib.comments app included with Django defines a {% get_comment_list %} template tag for retrieving comments attached to a given model instance. Here’s how you would use it:

<div>
{% load comments %}
{% get_comment_list for my_instance as comment_list %}
{% for comment in comment_list %}
  <p><a href="{{ comment.url }}">{{ comment.name }}</a> wrote:</p>
  {{ comment.comment }}
{% endfor %}
</div>

You could save this in a separate template and {% include %} it in other templates.

For your own content you can write your own custom template tags. Follow the documentation. Whenever possible, it’s convenient to write tags using the simple tag mechanism. You’ll find handy ready-made template tags on djangosnippets.org and the blogosphere.

6👍

👤S.Lott

Leave a comment