Skip to main content

Define your navigation in settings and simplify your templates.

Project description

Django Nav Spec

Define your site’s navigation in settings, and simplify your templates.

Rationale

A site’s navigation can be complex, and can lead to unwieldy templates full of repetitive and lengthy if conditionals to determine whether a particular navigation item should be displayed for the current user, or complicated logic to figure out which link is active for the current request. Add in dropdown menus where you only want the main dropdown to be visible if any of its children are, and your navigation bar template can quickly get out of hand.

django-nav-spec aims to simplify this, by defining your navigation in a single central place, and giving you the tools you need to easily mark a navigation item as active or remove it entirely based on the current request. Your template context receives a single object containing everything it needs to know to iterate and render your site’s navigation.

Features

  • Define navigation structures in your settings.py.
  • Supports single or multiple navigation menus.
  • Automatic active state detection based on URL names or custom logic.
  • Conditionally display navigation items based on user permissions or other request attributes.
  • Supports nested navigation structures.
  • Two usage modes: context processor (automatic) or template tag (on-demand).

Quick Start

Install django-nav-spec however you normally would:

pip install django-nav-spec
poetry add django-nav-spec
uv add django-nav-spec

Import NavigationItem in your settings and define your navigation as a list of items in the NAV_SPEC setting:

from nav_spec import NavigationItem

NAV_SPEC = [
    NavigationItem(title="Home", link="/", active_urls=["home"]),
    NavigationItem(title="About", link="/about/", active_urls=["about"]),
    NavigationItem(
        title="Admin",
        link="/admin/",
        displayed=lambda r: r.user.is_staff
    ),
]

Then choose one of two ways to use it in your templates:

Option 1: Context Processor (automatic)

Add the context processor to your project's settings:

TEMPLATES = [
    {
        ...
        'OPTIONS': {
            'context_processors': [
                ...
                'nav_spec.context_processors.nav_spec',
                ...
            ],
        },
    },
]

The navigation will automatically be available as NAV_SPEC in all templates:

<nav>
  <ul>
    {% for item in NAV_SPEC %}
    <li class="{% if item.is_active %}active{% endif %}">
      <a href="{{ item.link }}">{{ item.title }}</a>
    </li>
    {% endfor %}
  </ul>
</nav>

Option 2: Template Tag (on-demand)

Add nav_spec to your INSTALLED_APPS:

INSTALLED_APPS = [
    ...
    'nav_spec',
]

Load the template tag and call it where needed:

{% load nav_spec %}
{% get_nav_spec as nav %}

<nav>
  <ul>
    {% for item in nav %}
    <li class="{% if item.is_active %}active{% endif %}">
      <a href="{{ item.link }}">{{ item.title }}</a>
    </li>
    {% endfor %}
  </ul>
</nav>

When to use which approach:

  • Context Processor: Best when navigation is needed on every page. Processed automatically for all templates.
  • Template Tag: Best for selective use. Only processed when explicitly called, which can improve performance if navigation isn't needed everywhere.

This example may not look like it's saved you much, but the power comes as you add more items, hierarchy, or permissions. Read below for all the available options.

NavigationItem options

For each NavigationItem, ensure you set both its title and link for you to pull out in the template. In the examples above, the links are hard-coded URLs, but they could also be a reversed URL using django.urls.reverse_lazy:

from django.urls import reverse_lazy

NavigationItem(
    title="Blog",
    link=reverse_lazy("blog-index"),
)

Note: you must use reverse_lazy instead of reverse, as settings are evaluated before any URLs and reverse will fail.

Defining a NavigationItem’s active state

You can pass a list of URL pattern names to mark the item as active when any of the patterns are a match for the current URL:

NavigationItem(
    title="Blog",
    link="/blog/",
    active_urls=[
        "blog-index",
        "blog-post",
    ],
)

Or pass a function that takes a request object and returns True if the current item should be marked as active:

NavigationItem(
    title="Blog",
    link="/blog/",
    is_active=lambda request: True
)

In either case, the resulting NavigationItem object available in the template context will have a is_active property the template can use to toggle the item’s active state in the HTML/CSS.

Controlling whether a NavigationItem is displayed

You can control whether a navigation item appears in the final structure sent to the template with the displayed property. This can either be a string, which is used as a permission check:

NavigationItem(
    title="Comments",
    link="/comments/",
    displayed="blog.can_moderate_comments",
)

Or a callable that takes the request object and returns True if the item should be displayed:

NavigationItem(
    title="Admin",
    link="/admin/",
    displayed=lambda r: r.user.is_staff
)

Nested Navigation

To create nested navigation, use the children attribute:

# settings.py
NAV_SPEC = [
    NavigationItem(
        title="Products",
        children=[
            NavigationItem(title="Product A", link="/products/a/"),
            NavigationItem(title="Product B", link="/products/b/"),
        ]
    ),
]

A parent item will be considered active if any of its children are active. A parent item will be displayed if any of its children are displayed, or if it has its own displayed attribute that evaluates to True.

You can then render the nested navigation in your template:

<ul>
    {% for item in NAV_SPEC %}
    <li class="{% if item.is_active %}active{% endif %}">
        {% if item.link %}<a href="{{ item.link }}">{{ item.title }}</a>{% else %}{{ item.title }}{% endif %}
        {% if item.children %}
        <ul>
            {% for child in item.children %}
            <li class="{% if child.is_active %}active{% endif %}">
                <a href="{{ child.link }}">{{ child.title }}</a>
            </li>
            {% endfor %}
        </ul>
        {% endif %}
    </li>
    {% endfor %}
</ul>

Multiple Navigation Menus

You can define multiple navigation menus by setting NAV_SPEC to a dictionary:

# settings.py
NAV_SPEC = {
    "main_nav": [
        NavigationItem(title="Home", link="/", active_urls=["home"]),
    ],
    "footer_nav": [
        NavigationItem(title="Terms", link="/terms/", active_urls=["terms"]),
    ],
}

Then, in your template, you can access each menu as required:

With context processor:

<ul>
    {% for item in NAV_SPEC.main_nav %}
    ...
    {% endfor %}
</ul>

With template tag:

{% load nav_spec %}
{# Get a specific menu #}
{% get_nav_spec "main_nav" as main_nav %}
<ul>
    {% for item in main_nav %}
    ...
    {% endfor %}
</ul>

{# Or get all menus #}
{% get_nav_spec as all_nav %}
<ul>
    {% for item in all_nav.footer_nav %}
    ...
    {% endfor %}
</ul>

Customizing the Context Variable Name

Note: This only applies when using the context processor.

By default, the navigation is available in templates as NAV_SPEC. You can customize this by setting NAV_SPEC_CONTEXT_VAR_NAME:

# settings.py
NAV_SPEC_CONTEXT_VAR_NAME = 'navigation'

Then use the custom name in your templates:

{% for item in navigation %}
    ...
{% endfor %}

When using the template tag, you control the variable name directly in the template with the as clause.

Development

uv sync
uv run pytest

Requirements

  • Python 3.10+
  • Django 4.2+

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_nav_spec-1.0.0.tar.gz (43.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_nav_spec-1.0.0-py3-none-any.whl (7.1 kB view details)

Uploaded Python 3

File details

Details for the file django_nav_spec-1.0.0.tar.gz.

File metadata

  • Download URL: django_nav_spec-1.0.0.tar.gz
  • Upload date:
  • Size: 43.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for django_nav_spec-1.0.0.tar.gz
Algorithm Hash digest
SHA256 a4f0a370cb72f40e436578db38ac3d6b6a746116dfe763a769c6491471a19906
MD5 b7f6288204b317e106b05ca25af45a8b
BLAKE2b-256 d0dd930aad832dd4ef7ad661a103f4f1388adebd817960996e7e0073b6ba6ad3

See more details on using hashes here.

Provenance

The following attestation bundles were made for django_nav_spec-1.0.0.tar.gz:

Publisher: publish.yml on benbacardi/django-nav-spec

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file django_nav_spec-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for django_nav_spec-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 9c1cb1bb0bcf44839f5ce705e5604461f5a530f4c8ae4c58c8c6e450492dce8d
MD5 0aa0327930f9d9baad4590cbe044ac86
BLAKE2b-256 12ca4cb17e8cf12849e8766be834b81433455815a0558f015eb3680df0ad09ea

See more details on using hashes here.

Provenance

The following attestation bundles were made for django_nav_spec-1.0.0-py3-none-any.whl:

Publisher: publish.yml on benbacardi/django-nav-spec

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page