-1
<div class="menu-top" style="width:715px;">
  <ul class="nav nav-pills">
    <li>
      <a href="/link1"
      {% if request.path == '/phylosophy' %}class="active"{% endif %}>
      philosophy
      </a>
    </li>
    <li><a href="/link2"><u>{% trans 'product' %}</u></a></li>
    <li><a href="/link3"><u>{% trans 'contact' %}</u></a></li>
    <li><a href="/link4"><u>{% trans 'news' %}</u></a></li>
  </ul>
</div>

I need to add the class .active to the tag. What I'm doing wrong?

  • 1
    Possible duplicate of [Django dynamically get view url and check if its the current page](http://stackoverflow.com/questions/22047251/django-dynamically-get-view-url-and-check-if-its-the-current-page) – Sayse May 24 '16 at 08:30
  • 1
    Did you try printing `{{ request.path }}` to check if its value is really equal to what you are comparing to? – Selcuk May 24 '16 at 09:33

1 Answers1

2

Normally Django appends / to the URLs, so it might be the case of changing to:

{% if request.path == '/phylosophy/' %}class="active"{% endif %}>

Extra:

The thing with this approach is that, if you have a deeper URL like /phylosophy/list/, you may still want to keep the active class, so what I usually do is creating a templatetag called startswith:

@register.filter('startswith')
def startswith(text, starts):
    if isinstance(text, basestring):
        return text.startswith(starts)
    return False

And then use it like:

<li{% if request.path|startswith:'/phylosophy/' %} class="active"{% endif %}>

PS:

In case request.path is empty when you print it, you might need to add it to your context processors (django.template.context_processors.request), example:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'APP_DIRS': True,
        'DIRS': (
            PROJECT_DIR.child('templates'),
        ),
        'OPTIONS': {
            'context_processors': [
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.debug',
                'django.template.context_processors.i18n',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.request',
            ],
            'debug': DEBUG
        }
    },
]
Vitor Freitas
  • 3,550
  • 1
  • 24
  • 35