Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: how to get the name of the template being rendered

I'm implementing a bootstrap navbar as show in this example here

Items in a navbar are <li>'s , the "selected" item has the attribute class="active":

  <li class="active"> <a href="#"> Link1 </a> </li>
  <li>                <a href="#"> Link2 </a> </li>

In Django these items will be within a template, which gets included by any templates that are supposed to display the navbar. I'm thinking about doing it this way:

<li> <a href="/"        class="{% if template_name == "home.djhtml"    %}active{% endif %}"> Home    </a> </li>
<li> <a href="about/"   class="{% if template_name == "about.djhtml"   %}active{% endif %}"> About   </a> </li>
<li> <a href="contact/" class="{% if template_name == "contact.djhtml" %}active{% endif %}"> Contact </a> </li>

I would like to know if there is a built-in way to get the template_name (that is, the template being rendered, as passed to render_to_response(), in views.py)

Sure, I could explicitly add a template_name variable to render_to_response(), which would solve the problem. But thinking about DRY I feel this shouldn't be needed.

like image 550
E.Z. Avatar asked Oct 09 '13 09:10

E.Z.


1 Answers

I usually use a custom template tag for this use case of adding a class to the active tab, menu item, etc.

@register.simple_tag
def active_page(request, view_name):
    from django.core.urlresolvers import resolve, Resolver404
    if not request:
        return ""
    try:
        return "active" if resolve(request.path_info).url_name == view_name else ""
    except Resolver404:
        return ""

And here's a snippet from the top nav:

<ul class="nav">
    <li class="{% active_page request "about" %}"><a href="{% url "about" %}">About</a></li>
    ...
</ul>
like image 125
Kevin Stone Avatar answered Oct 09 '22 16:10

Kevin Stone