Probably every project has a navigation system - users click on links, menus and we (developers \ designers \ layout designers) need to somehow “highlight” the page \ link on which the user is currently located.
I provide a non-trivial solution to a very trivial task when developing navigation in Django projects.
For non-patient, you can immediately look at the
project on github .
The most trivial solution
In each view, in the context, we pass a certain variable, let it be “location” and then ruthlessly hardkim:
')
<ul> <li {% if location=='random_page' %} class="active" {% endif %}> <a href="{% url 'random_page' %}"> {% trans 'random page' %} </a> </li> </ul>
It turns out - each link has a unique value of “location”, which generates a lot of unnecessary code, when there are many links / views it is practically impossible to remember which “location” to which link, as well as the coder can be extremely dissatisfied with the need to delve into the Python logic view and what value from where falls into context.
You can transfer the “location” is the same as the name link of this view and the navigation will become slightly more visual.
Implementation through a simple “template filter”
filter proper:
from django import template register = template.Library() def active(url, request): if url == request.get_full_path(): return True else: return False register.filter('active', active)
further in the template:
{% load active %} <ul> {% url 'random_page' as random_page %} <li {% if random_page|active:request %} class="active" {% endif %}> <a href="{{ random_page }}"> {% trans 'random page' %} </a> </li> </ul>
You no longer need to transfer variables with views, you can replace the comparison with .startswith () or even regular ones and add support for the menu, for example, shine a link to "/ menu /" when the user is on the page "/ menu / submenu /". But the routine has not gone anywhere ...
My bikes - django-activeurl
Routine actions are completely absent, namely:
{% load activeurl %} {% activeurl %} <ul> <li> <a href="{% url 'random_page' %}"> {% trans 'random page' %} </a> </li> </ul> {% endactiveurl %}
a little magic ...
<ul> <li class="active"> <a href="/random_page/"> random page </a> </li> </ul>
Installation as with all Python batteries:
pip install django-activeurl
All the nuances are described
here .
Now, a little about how it all works - a tree is constructed from the transmitted html using
lxml , it searches for HTML elements that need to be highlighted (default is “li”), then all links are taken in this tag and their “href” parameter is compared with "request.get_full_path ()".
Implemented features:
Less all routine tasks in the development!