user3541631
user3541631

Reputation: 4008

Compare urls in Django Template

In a django template I don't want to show some element in case if the url/path is a specific one. In pseudo:

 {% if not url = account:detail %}

Upvotes: 2

Views: 1194

Answers (2)

Aniket Pawar
Aniket Pawar

Reputation: 2721

You can give your urls a name ( url_name ) in urls.py file and then you can compare directly using HttpRequest.resolver_match object available in template.

from django.urls import path
from . import views

urlpatterns = [
    path('articles/<int:year>/', views.year_archive, name='news_year_archive'),
    # ...
]

In template you compare it like,

{% if request.resolver_match.url_name == "news_year_archive" %}
   ...your stuff
{% endif %}

Upvotes: 3

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477533

We can do this in two steps here:

  1. first we resulve the url, and assign it to a variable (here url2); and
  2. next compare the urls

So:

{% url account:detail as url2 %}
{% if url != url2 %}
    <!-- ... (do something) ... -->
{% endif %}

Note however that if two urls are syntactically different (for example yourdomain.com/foo and /foo), that they per se point to something different.

If you want access to the current path, you can - like @RajaSimon says, usually use request.path (given you render the template with a RequestContext, render(..), or another way to pass the request object).

Upvotes: 3

Related Questions