Skip to content

Template patterns

Django's template language is quite simple. However, you can save a lot of time by following some elegant template design patterns.

Solution

There are several solutions to determine the active link. Excluding JavaScript-based approaches, they can be mainly grouped into template-only and custom tag-based solutions.

<ul class="nav">
    <li class="{% if request.path == '/' %}active{% endif %}">
        <a href="/">Home</a>
    </li>
    <li class="{% if request.path == '/about/' %}active{% endif %}">
        <a href="/about/">About</a>
    </li>
</ul>
nav.py
from django.urls import resolve
from django import template

register = template.Library()

@register.simple_tag
def active_nav(request, url):
    url_name = resolve(request.path).url_name

    print("url :", urls , " , url_name: ", url_name)

    if url_name == url:
        return "active"
    return ""

# slighly advanced
@register.simple_tag
def active_nav(request, *urls):
    url_name = resolve(request.path).url_name

    print("url :", urls , " , url_name: ", url_name)

    if url_name in urls:
        return "active"
    return ""

Note

In Django, it's standard practice to keep custom template tags within the app they belong to, usually in a templatetags directory within the app's directory structure. This convention helps maintain a clear separation of concerns and promotes modularity and reusability.

While it's technically possible to place templatetags outside of the app, it's generally not recommended unless there's a compelling reason to do so. Placing templatetags outside of the app may lead to a less organized codebase and make it harder for developers to understand the relationships between different components.

However, if you have templatetags that are generic and reusable across multiple apps or even across different projects, you might consider creating a separate reusable Django app specifically for those templatetags. This approach allows you to centralize reusable functionality while still maintaining modularity and encapsulation.


Reference