【问题标题】:Django - Change active navbar template based on webpageDjango - 根据网页更改活动导航栏模板
【发布时间】:2016-12-13 00:35:39
【问题描述】:

我的 html 中有一个看起来像这样的模板。它使用引导类。

  <-- navbar-template.html>
  <div class="collapse navbar-collapse" id="myNavbar">
    <ul class="nav navbar-nav">
      <li><a href="/home/">Home</a></li>
      <li class='active'><a href="/members/">Members</a></li>
      <li><a href="#">Research</a></li> 
      <li><a href="#">Publications</a></li>
      <li><a href="#">Links</a></li>  
    </ul>
    <ul class="nav navbar-nav navbar-right">
      <li><a href="#"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
    </ul>
  </div>

我喜欢活动类,但我需要根据 django 导航栏加载的页面来更改它是哪个列表对象。

我想你想在 home.html 文件中做这样的事情

<-- HOME -->
{% include "navbar_template.html" with page="home"}  %}

###Do something with {{page}} variable in order to set the home list tag to active.

我必须写大量的 if else 语句还是有更简单的方法。也许与 django 中的 views.py 有什么关系

【问题讨论】:

    标签: django twitter-bootstrap django-templates


    【解决方案1】:

    你可以这样做(我在我的页面上使用的示例解决方案):

    <ul class="sidebar-nav--primary">
      {% url 'main:home' as home %}
      {% url 'main:work' as work %}
      {% url 'main:personal' as personal %}
    
      <li><a href="{{ home }}" {% if request.path == home %}class="active"{% endif %}>Home</a></li>
      <li><a href="{{ work }}" {% if request.path == work %}class="active"{% endif %}>Work</a></li>
      <li><a href="{{ personal }}" {% if request.path == personal %}class="active"{% endif %}>Personal</a></li>
    
    </ul>
    

    【讨论】:

      【解决方案2】:

      更简洁的方法是创建custom template tag。类似is_active:

      # Inside custom tag - is_active.py
      from django.template import Library
      from django.core.urlresolvers import reverse
      register = Library()
      
      @register.simple_tag
      def is_active(request, url):
          # Main idea is to check if the url and the current path is a match
          if request.path in reverse(url):
              return "active"
          return ""
      

      并像这样在您的模板中使用它:

      # template.html
      {% load is_active %}
      <li><a href="{% url 'home' %}" class="{% is_active request 'home' %}">Home</a></li>
      

      【讨论】:

      猜你喜欢
      • 2018-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-05
      • 1970-01-01
      • 1970-01-01
      • 2017-08-21
      • 1970-01-01
      相关资源
      最近更新 更多