且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 django 导航栏下拉列表中显示活动链接?

更新时间:2022-04-05 23:13:51

如果您使用以下名称定义 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.