[Django]-Factorizing a header menu in Django template

3👍

If you have a “page” object at every view, you could compare a navigation item’s slug to the object’s slug

navigation.html

<ul>
    {% for page in navigation %}
        <li{% ifequal object.slug page.slug %} class="active"{% endifequal %}>
            <a href="{{ page.get_absolute_url }}">{{ page.title }}</a>
        </li>
    {% endfor %}
</ul>

base.html

<html>
    <head />
    <body>
        {% include "navigation.html" %}
        {% block content %}
            Welcome Earthling.
        {% endblock %}
    </body>
</html>

page.html

{% extends "base.html" %}

{% block content %}
    {{ object }}
{% endblock %}

Where navigation is perhaps a context_processor variable holding all the pages, and object is the current PageDetailView object variable

Disclaimer

There are many solutions for your problem as noted by Paulo. Of course this solution assumes that every view holds a page object, a concept usually implemented by a CMS. If you have views that do not derive from the Page app you would have to inject page pretenders within the navigation (atleast holding a get_absolute_url and title attribute).

This might be a very nice learning experience, but you’ll probably save loads time installing feinCMS or django-cms which both define an ApplicationContent principle also.

6👍

You can create a custom templatetag:

from django import template
from django.core.urlresolvers import reverse, NoReverseMatch, resolve

register = template.Library()

@register.simple_tag
def active(request, view_name):
    url = resolve(request.path)
    if url.view_name == view_name:
        return 'active'
    try:
        uri = reverse(view_name)
    except NoReverseMatch:
        uri = view_name
    if request.path.startswith(uri):
        return 'active'
    return ''

And use it in the template to recognize which page is loaded by URL

<li class="{% active request 'car_edit' %}"><a href="{% url 'car_edit' car.pk %}">Edit</a></li>

1👍

You may use the include tag and pass it a value which is the current page.

For example, this may be a separate file for declaring the menu template only:

menu.html

{% if active = "a" %}
<li><a href="{% url 'myapp:index' %}">Home</a></li>
{% if active = "b" %}
<li><a href="{% url 'myapp:page1' %}">page1</a></li>
{% if active = "c" %}
<li class="active"><a href="{% url 'myapp:page2' %}">page2</a></li>
{% if active = "d" %}
<li><a href="{% url 'myapp:page3' %}">page3</a></li>

And call this from within your template like this:

{% include 'path/to/menu.html' with active="b"%} # or a or c or d.

Hope it helps!

Leave a comment