如何在 django 导航栏下拉列表中显示活动链接? [英] How do i show an active link in a django navigation bar dropdown list?
问题描述
我有一个带有链接列表的导航栏菜单,当用户在页面上时,我想显示活动链接,到目前为止,我已经设法使用没有下拉菜单的链接来做到这一点.
I have a navbar menu with a list of links which i want to show the active link when the user is on the page, so far i have managed to do this with links that dont have dropdowns like this.
但我似乎无法正确使用下拉链接,如果用户在下拉链接上的页面上,导航栏上的父链接会突出显示.如下所示
But I cannot seem to get it right with the dropdown links in such a way that if the user is on a page on the dropdown link the parent link on the navbar gets highlighted.like shown below
任何帮助将不胜感激.
推荐答案
如果您使用以下名称定义 URL:
If you define your URLs with names like this:
url('', 'home_view', name='home'),
url('posts/', 'posts_view', name='blog'),
url('contact/', 'contact_view', name='contact'),
您可以在模板中使用这些名称来使 if 语句起作用:
You can use these names in the template to make the if statements work:
{% with request.resolver_match.url_name as url_name %}
<ul id="menu">
<li class="{% if url_name == 'home' %}active{% endif %}">Home</li>
<li class="{% if url_name == 'blog' %}active{% endif %}">Posts</li>
<li class="{% if url_name == 'contact' %}active{% endif %}">Contact</li>
</ul>
{% endwith %}
这样可以避免重复 url 路径的问题.
This saves you from problems with duplication in url paths.
这篇关于如何在 django 导航栏下拉列表中显示活动链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!