Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Templates: Comparing current url with {% url xyz %}

I am trying change the active selection of my navigation links based on the current page where the user is at.

I am trying to do omething like this:

<li {% if request.get_full_path == {% url profile_edit_personal %} %}class="current"{% endif %}><a href="{% url profile_edit_personal %}">Personal Details</a></li>

Alternatively, I know I could define do something like this:

<li class="{% block current %}{% endblock %}"><a href="{% url profile_edit_personal %}">Personal Details</a></li>

and add a {% block current %}current{% endblock %} to each of the relevant templates but I would prefer something like what Im trying to achieve in the first example if possible

Thanks!

like image 236
super9 Avatar asked Sep 29 '11 07:09

super9


Video Answer


1 Answers

Since you'll probably only need to do this once--in your nav template--it makes more sense to me to keep everything in one place.

First reverse your url names and store them in variables like Timmy suggested, then simply compare them in the template:

{% url 'about_page' as about %}
...

<ul id="nav">
    <li class="{% ifequal request.path about %}active{% endifequal %}"><a href="{{about}}">About</a></li>
...

Just make sure you have your request context processor enabled so you have access to the request in the template. Do this by adding django.core.context_processors.debug in your TEMPLATE_CONTEXT_PROCESSORS settings variable.

like image 88
nullability Avatar answered Oct 10 '22 19:10

nullability