Django - 根据网页更改活动导航栏模板

时间:2016-08-06 21:19:26

标签: django twitter-bootstrap django-templates

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

import itertools
l = [1, 2, 3, 4]
nl = itertools.combinations(l, 2)
nl = list(nl)
print nl

我喜欢活动类,但我需要更改哪个列表对象基于导航栏django中加载的哪个页面。

我想你想在home.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>

我是否必须编写一些疯狂的if else语句,或者是否有更简单的方法。也许与django中的views.py有关。

2 个答案:

答案 0 :(得分:2)

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

  implicit class SeqAugmenter[T](val seq: Seq[T]) extends AnyVal {
    def intersect(opt: Option[Seq[T]]): Seq[T] = {
      opt.fold(seq)(seq intersect _)
    }
  }

  def getFilteredList(ids: Seq[Int],
    idsMustBeInThisListIfItExists: Option[Seq[Int]],
    idsMustAlsoBeInThisListIfItExists: Option[Seq[Int]]
  ): Seq[Int] = {
    ids intersect
      idsMustBeInThisListIfItExists intersect 
      idsMustAlsoBeInThisListIfItExists
  }

答案 1 :(得分: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>