📅  最后修改于: 2023-12-03 15:30:30.276000             🧑  作者: Mango
在 Django 中,我们可以通过在模板中使用 django.template.context_processors.request
上下文处理器和 request
对象的 path
属性来确定当前页面的 URL,从而在导航栏中设置活动状态。
以下是一些设置导航栏处于活动状态的方法。
Django 内置的 url
标签可以用于生成 URL,也可以用于检查当前页面的 URL 是否与给定的 URL 匹配。在 url
标签中使用 as
子句将 URL 保存到模板变量中,然后使用 if
语句检查当前页面的 URL 是否与该变量匹配。
{% url 'home' as home_url %}
<a href="{{ home_url }}" {% if request.path == home_url %}class="active"{% endif %}>Home</a>
如果你需要频繁地为导航栏添加活动状态,那么可以编写一个自定义模板标签来简化代码。
from django import template
register = template.Library()
@register.simple_tag
def active(request, pattern):
"""
Returns the string 'active' if the pattern matches the request's path, otherwise returns an empty string.
"""
import re
if re.search(pattern, request.path):
return 'active'
return ''
{% load my_template_tags %}
<a href="/" class="{% active request '^/$' %}">Home</a>
<a href="/blog/" class="{% active request '^/blog/' %}">Blog</a>
<a href="/about/" class="{% active request '^/about/' %}">About</a>
还可以在视图中设置活动状态并将其传递到模板中。这种方法需要在每个视图中手动设置活动状态。
from django.shortcuts import render
def home(request):
return render(request, 'home.html', {'home_active': True})
def blog(request):
return render(request, 'blog.html', {'blog_active': True})
def about(request):
return render(request, 'about.html', {'about_active': True})
<a href="/" {% if home_active %}class="active"{% endif %}>Home</a>
<a href="/blog/" {% if blog_active %}class="active"{% endif %}>Blog</a>
<a href="/about/" {% if about_active %}class="active"{% endif %}>About</a>
以上三种方法都可以用于在 Django 中设置导航栏处于活动状态。使用自己喜欢的方法并添加样式来使导航栏更加易于使用和可视化。