Skip to content Skip to sidebar Skip to footer

Compare Request.path With A Reversed Url In Django Template

I understand that request.path will give me the current URL. I am currently working on my base.html template with CSS tabs and I want the template to know which tab is currently 'a

Solution 1:

Building on Josh's answer, you can use a simple 'if' tag:

{% url 'orders_list'as orders_list_url %}
<a{% if request.path == orders_list_url %} class="active"{% endif %}
  href="{{ orders_list_url }}">Orders</a>

Solution 2:

A better version of the top answer would be to reverse the viewname:

{% url_active 'reverse_viewname' %}

This version doesn't require you to pass in the request. Instead, we indicate that the tag needs the context and then get the request from that.

from django import template
from django.core.urlresolvers import reverse

register = template.Library()

@register.simple_tag(takes_context=True)defurl_active(context, viewname):
    request = context['request']
    current_path = request.path
    compare_path = reverse(viewname)
    if current_path == compare_path:
        return'active'else:
        return''

Solution 3:

You can use a custom template tag

from django importtemplateregister= template.Library()

@register.simple_tag
def active(request, pattern):
    path = request.path
    ifpath== pattern:
        return'active'return''

Then usage is sort of like this in your template:

{% load my_tags %}

{% url orders_list as orders %}
<li class="{% active request orders %}"> 
    <ahref="{{ orders }}"> Orders </a> 
</li>

You can modify the template tag as you wish.

Solution 4:

Inspired by cougar's answer:

$("ul.nav [href='"+window.location.pathname+"']").parents("li").addClass('active');

This solution is plain JS, and works for Bootstrap's navigation bar. For the OP's scenario one can use:

$("[href='"+window.location.pathname+"']").addClass('active-tab');

Solution 5:

A solution with an if-then-else option:

from django import template
from django.template.base import Node, NodeList, TemplateSyntaxError

register = template.Library()

classIfCurrentViewNode(Node):
    child_nodelists = ('nodelist_true', 'nodelist_false')

    def__init__(self, view_name, nodelist_true, nodelist_false):
        self.view_name = view_name
        self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false

    def__repr__(self):
        return"<IfCurrentViewNode>"defrender(self, context):
        view_name = self.view_name.resolve(context, True)
        request = context['request']
        if request.resolver_match.url_name == view_name:
            return self.nodelist_true.render(context)
        return self.nodelist_false.render(context)


defdo_ifcurrentview(parser, token):
    bits = token.split_contents()
    iflen(bits) < 2:
        raise TemplateSyntaxError("'%s' takes at least one argument"" (path to a view)" % bits[0])
    view_name = parser.compile_filter(bits[1])
    nodelist_true = parser.parse(('else', 'endifcurrentview'))
    token = parser.next_token()
    if token.contents == 'else':
        nodelist_false = parser.parse(('endifcurrentview',))
        parser.delete_first_token()
    else:
        nodelist_false = NodeList()
    return IfCurrentViewNode(view_name, nodelist_true, nodelist_false)

@register.tagdefifcurrentview(parser, token):
    """
    Outputs the contents of the block if the current view match the argument.

    Examples::

        {% ifcurrentview 'path.to.some_view' %}
            ...
        {% endifcurrentview %}

        {% ifcurrentview 'path.to.some_view' %}
            ...
        {% else %}
            ...
        {% endifcurrentview %}
    """return do_ifcurrentview(parser, token)

Post a Comment for "Compare Request.path With A Reversed Url In Django Template"