[Django]-How to get something to appear on every page in Django?

16👍

You want a context processor. The data they generate is included in every context created as a RequestContext. They are perfect for this.

Combined with base templates that show common things, you can get rid of lots of need for copying and pasting code.

3👍

use inheritance in the templating engine:

have a base.html that includes the common code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<link rel="stylesheet" href="style.css" />
<title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
<div id="sidebar">
    {% block sidebar %}
    <ul>
        <li><a href="/">Home</a></li>
        <li><a href="/blog/">Blog</a></li>
    </ul>
    {% endblock %}
</div>

<div id="content">
    {% block content %}{% endblock %}
</div>
</body>
</html>

then in each page that needs that common code, simply:

{% extends "base.html" %}
{% block title %}My amazing blog{% endblock %}
{% block content %}
{% for entry in blog_entries %}
<h2>{{ entry.title }}</h2>
<p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}

http://docs.djangoproject.com/en/dev/topics/templates/#id1

this combined with context processessing will eliminate a lot of duplicate code.

2👍

Middleware is one option or your could write a custom template tag.

0👍

To do exactly what you request, I’d simply define a function:

def foobar(req):
    return render_to_response(
        "core/index.html",
        {
            "locality": getCityForm(req.user),
        },
        context_instance=RequestContext(req)
    )

put it in some module myfun, and return myfun.foobar(request) wherever needed. You’re likely to want a few more arguments, but as long as it stays about this simple, it’s simpler that defining middleware, using OOP, &c.

Leave a comment