如何使用Django标签为多个网址设置“活动”导航栏链接

时间:2019-01-23 17:34:21

标签: django django-templates

我有以下代码

navbar.html

{% url 'news:list' as news_url %}
{% url 'news:list-detail' as news_url_detail %}
[..]    
<ul class="navbar-nav">
 [..]        
 <li class="nav-item ">
   <a class="nav-link {% if request.path == news_url %}active{% endif %}" href="{{ news_url }}">News<span class="sr-only">(current)</span>
   </a>
 </li>
</ul>

我的目标是将导航栏链接“新闻”设置为活动状态,即使当前网址不是“新闻”(news_url

<a class="nav-link {% if request.path == news_url or request.path == news_url_detail %}active{% endif %}" href="{{ news_url }}">News<span class="sr-only">(current)</span>

我该怎么办?

感谢您提供的任何帮助。

编辑1 /core/app/urls.py

urlpatterns = [
    [..]
    url(r'^newsandeventi/', include("newsandeventi.urls", namespace='newsandeventi')),
    [..]
]

/newsandeventi/urls.py

from django.conf.urls import url, include
from newsandeventi.views import ArchiveView, CategoryListView, SearchView, EntryDetailView
# from blog.views import EntryDetailView, CategoryListView, ArchiveView, SearchView, SearchResultView # noqa


urlpatterns = [
    url(r'^$', ArchiveView.as_view(), name='list'),
    url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$', EntryDetailView.as_view(), name='list-detail'),    
    url(r'^categoria/(?P<tag>[-\w .]+)/$', CategoryListView.as_view(), name='category-list'),
]

编辑2: /newsandeventi/views.py

class EntryDetailView(DetailView):
    model = Entry
    paginate_by = 1

    def get_queryset(self):
        return Entry.objects.published()

    def get_context_data(self, **kwargs):
        context = super(EntryDetailView, self).get_context_data(**kwargs)
        context['base_url'] = self.request.build_absolute_uri("/").rstrip("/")
        context['alltags'] = Tag.objects.all()
        context['fiveposts'] = Entry.objects.order_by('id')[:5]
        entries= Entry.objects.all()
        context['last_featured'] = entries.filter(featured=True).last()
        return context

问题可能来自基于类的视图EntryDetailView,当我调用newsandeventi:list-detail时,我没有传递参数year, month, day, slug

如果这是问题,我该如何解决?

1 个答案:

答案 0 :(得分:1)

问题是这一行:

{% url 'news:list-detail' as news_url_detail %}

将以静默方式失败,因为您未传递URL要求的年/月/日/段参数。如果视图查找失败,则使用{% url ... as var %}语法does not cause an error

识别呈现的页面是否为EntryDetailView的更好方法可能是在上下文数据中设置一个标志,然后测试该标志的存在。

例如:

class EntryDetailView(DetailView):
    ...

    def get_context_data(self, **kwargs):
        ...
        context['is_entry'] = True  # Set a flag
        return context

然后在模板中:

<a class="nav-link {% if request.path == news_url or is_entry %}active{% endif %}" href="{{ news_url }}">News<span class="sr-only">(current)</span>