Question

I am wondering if someone can help me figure out the best approach to the following problem. I'm building a web application which uses Django templating to construct its web UI component. There are a number of common HTML elements such as the header / footer, HTML head, masthead etc. I'd like to code these once and "include/combine" them with other templates representing the core application functionality.

Is this possible using Django Templates? If so how might I go about accomplishing that?

Was it helpful?

Solution

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/.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top