Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h1>Using template tag</h1> <p>You can simply use the following template tag:</p> <pre><code># path/to/templatetags/mytags.py import re from django import template from django.core.urlresolvers import reverse, NoReverseMatch register = template.Library() @register.simple_tag(takes_context=True) def active(context, pattern_or_urlname): try: pattern = '^' + reverse(pattern_or_urlname) except NoReverseMatch: pattern = pattern_or_urlname path = context['request'].path if re.search(pattern, path): return 'active' return '' </code></pre> <p>So, in you your template:</p> <pre><code>{% load mytags %} &lt;nav&gt;&lt;ul&gt; &lt;li class="nav-home {% active 'url-name' %}"&gt;&lt;a href="#"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li class="nav-blog {% active '^/regex/' %}"&gt;&lt;a href="#"&gt;Blog&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;&lt;/nav&gt; </code></pre> <h1>Using only HTML &amp; CSS</h1> <p>There is another approach, using only HTML &amp; CSS, that you can use in any framework or static sites.</p> <p>Considering you have a navigation menu like this one:</p> <pre><code>&lt;nav&gt;&lt;ul&gt; &lt;li class="nav-home"&gt;&lt;a href="#"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li class="nav-blog"&gt;&lt;a href="#"&gt;Blog&lt;/a&gt;&lt;/li&gt; &lt;li class="nav-contact"&gt;&lt;a href="#"&gt;Contact&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;&lt;/nav&gt; </code></pre> <p>Create some base templates, one for each session of your site, as for example:</p> <pre><code>home.html base_blog.html base_contact.html </code></pre> <p>All these templates extending <code>base.html</code> with a <em>block</em> "section", as for example:</p> <pre><code>... &lt;body id="{% block section %}section-generic{% endblock %}"&gt; ... </code></pre> <p>Then, taking the <code>base_blog.html</code> as example, you must have the following:</p> <pre><code>{% extends "base.html" %} {% block section %}section-blog{% endblock %} </code></pre> <p>Now it is easy to define the actived menu item using CSS only:</p> <pre><code>#section-home .nav-home, #section-blog .nav-blog, #section-contact .nav-contact { background-color: #ccc; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload