1

I`m new with django (came from Grails), especially with all those custom tags that you have to deal with, instead of writing your variables directly inside the templates.

Well, what I need to do was something really simple, but for some reason is taking me a long time to finish. What I wish to do was make a tag that checks for me if the given path is equals my current url, and then returns the class if true.

<li class="{% check_url '/login/' 'current_page_item' %}">
    <a href="{% url social_login %}">login</a>
</li>

But, the problem came when I tried to register the tag with takes_context :

Caught TypeError while rendering: simple_tag() got an unexpected keyword argument 'takes_context'

from django import template

register = template.Library()

@register.simple_tag(takes_context=True)
def check_url(context, path, attr):
        if context['request'].environ.get('PATH_INFO') == path:
            return attr
        else:
            return ''

How can I fix it? Also, is there a better way to do it?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
mateusmaso
  • 7,843
  • 6
  • 41
  • 54
  • 3
    Are you using hte latest development version of django (1.3.x?) or the stable 1.2.x? If so you can't use simple_tag in this way - http://docs.djangoproject.com/en/dev/howto/custom-template-tags/ . A simple quick way is perhaps to do something like {% ifequal request.get_full_path '/login/' %}class="current_page"{% endif %}. – user608133 Mar 08 '11 at 20:44
  • 1
    I`m using django 1.2.5, I tried to do the quick way before, but I moved to custom tag for a clean view. The takes_context only works with inclusion_tag(not what I want) – mateusmaso Mar 08 '11 at 20:50

2 Answers2

2

That's because takes_context is only available since django 1.3.

dragoon
  • 5,601
  • 5
  • 37
  • 55
1

Another approach to do it (and to avoid hardcoded urls):

{% url social_login as the_url %}
{% ifequal the_url request.path %}
....
{% endif %}

Or check out something like this!

Bernhard Vallant
  • 49,468
  • 20
  • 120
  • 148