Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 "active" and pass class="active-tab" to an <a> tag.

So I wanted to do something like

<a href="{% url orders_list %}"
    {% if request.path = reverse('orders_list') %}
        class="active-tab"
    {$ endif %}
>Orders</a>

But I'm sure you can't do that if comparison. I also only want the base (?) URL ignoring any GET parameters.

Any suggestions or tips also welcomed. Thanks in advance!

like image 781
hobbes3 Avatar asked Apr 21 '12 22:04

hobbes3


People also ask

What does the Django urls reverse () function do?

reverse_lazy()providing a reversed URL as the url attribute of a generic class-based view. providing a reversed URL to a decorator (such as the login_url argument for the django.

What does {{ this }} mean in Django?

{{ foo }} - this is a placeholder in the template, for the variable foo that is passed to the template from a view. {% %} - when text is surrounded by these delimiters, it means that there is some special function or code running, and the result of that will be placed here.

What is the difference between path and URL in Django?

In Django 2.0, you use the path() method with path converters to capture URL parameters. path() always matches the complete path, so path('account/login/') is equivalent to url('^account/login/$') . The part in angle brackets ( <int:post_id> ) captures a URL parameter that is passed to a view.

How can I get previous URL in Django?

You can do that by using request. META['HTTP_REFERER'] , but it will exist if only your tab previous page was from your website, else there will be no HTTP_REFERER in META dict . So be careful and make sure that you are using . get() notation instead.


1 Answers

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>
like image 138
macro Avatar answered Oct 06 '22 01:10

macro