I am using Django and integrated Bootstrap with Django. Here is my HTML code for the navigation bar:
I would rather prefer to only edit the template using rather than editing both views and templates for this. People needing the same, rather than following the accepted answer, may consider the below way:
<ul class="navbar-nav">
<li class="nav-item {% ifequal request.path '/' %} active {% endifequal %}">
<a class="nav-link" href="/">Home</a>
</li>
</ul
You can change 'index' above with your own
I recently ran into this problem and tried every solution I could find. Eventually, I came to this. This example assumes the path to this content is yoursite.com/about Give your link an id.
<li><a id="about" href="#">About</a></li>
var path = $(location).attr('pathname')
var pa = path.split("/")
$('#'+pa[1]).tab('show')
@rphonika has give a nice answer. But if you have many navigation menus then adding template logic in each list item makes the code untidy. Menu items can be assigned a unique id, the id passed in views and active class can be assigned using a one liner javascript code in html itself.
base.html
<ul class="nav navbar-nav navbar-left">
<li><a class="navmenu-a" id="overview" href="{% url 'webapp:overview' %}">Overview</a></li>
<li><a class="navmenu-a" id="plot" href="{% url 'webapp:plot' %}">Plot</a></li>
<li><a class="navmenu-a" id="board" href="{% url 'webapp:board' %}">Board</a></li>
<li><a class="navmenu-a" id="storyboard" href="{% url 'webapp:storyboard' %}">Storyboard</a></li>
<li><a class="navmenu-a" id="freqs" href="{% url 'webapp:freqs' %}">Faq</a></li>
</ul>
.
.
.
<script type="text/javascript">
{% if nmenu %} $("a#{{nmenu}}").addClass("navmenu-a-active") {% endif %}
</script>
views.py
def overview(request):
...
return render(request, 'overview.html', {'nmenu': 'overview'})
def plot(request):
...
return render(request, 'plot.html', {'nmenu': 'plot'})
And so on for other views
If you want activate by context you can do like this variable == to context in .views
<li class="nav-item {% ifequal variable context %}active{% endifequal%}">
<a class="nav-link" href="{% url 'scores:list' %}">Scores</a>
</li>
If you dont want to send any additional context from views then you can handle it like this with resolver_match:
<li {% if request.resolver_match.url_name == 'home' %}class="active"{% endif %}>
<a href="/">HOME</a>
</li>
where 'home' is the name given to your url pattern for / (probably '^$'
) in your urls.py.
So obviously to use this you need to name all your url patterns, which is a good practice anyway.
you can just add jquery between
<script type="text/javascript">
</script>
in you html