views:

51

answers:

3

In a Django template, how could I refer to the URL. I want to use it in static pages, to avoid having live links to the current page. Is there a way to do this with the Django template language or do I have to use JavaScript to do it?

I would like to do something like

{% if current_url == "/about/" %}
About
{% else %}
<a href='/about/'>About</a>
{% endif %}

I'm using it for a simple blog, so there are no views written for those pages.

+1  A: 

instead of current_url in your example above, you can substitute request.path (assuming you've got django.core.context_processors.request in play). And it'd have to be == not = :o)

stevejalim
I have been trying to add django.core.context_processors.request to the settings files (and a range of related settings), but I still don't get it to work. I had assumed (wrongly) that it would be really simple to do with Django.
Vernon
It is pretty simple to do. Can you paste your settings.py into the question above (or at least the TEMPLATE_CONTEXT_PROCESSORS tuple) so we can have a look?
stevejalim
When I first asked the question, I didn't have any TEMPLATE_CONTEXT_PROCESSORS in my settings file. I have added:TEMPLATE_CONTEXT_PROCESSORS = ( "django.contrib.auth.context_processors.auth", "django.core.context_processors.request", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.contrib.messages.context_processors.messages")
Vernon
And is it working?
stevejalim
+2  A: 

I presume by your reference to 'static pages' you mean generic views. Internally, these use RequestContext, so you have access to the request object which is the current HttpRequest. So you can access the current URL with request.path.

{% if request.path == '/about/' %}
...
{% endif %}

Note that this if syntax is Django 1.2+ only - if you're using an older version, you have to do:

{% ifequal request.path '/about/' %}
...
{% endifequal %}
Daniel Roseman
I have tried that, but it didn't seem to work. The Django version is 1.2.1.
Vernon
A: 

I think you can accomplish this with simple template inheritance:

# base.html
{% block contactlink %}<a href='/contact/'>Contact</a>{% endblock %}
{% block aboutlink %}<a href='/about/'>About</a>{% endblock %}
  ...

# about.html
{% block aboutlink %}About{% endblock %}

# contact.html
{% block contactlink %}Contact{% endblock %}

Of course this only works if you have a separate template for each page, but I'm assuming you do since you said the pages are static. Knowing more about what views you are using (assuming generic view direct_to_template or similar) and your urls.py would help.

Chris Lawlor
SO syntax highlighting apparently does not like django template syntax mixed with python comments.
Chris Lawlor