Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template, if tag based on current URL value

Tags:

django

I want to be able to do an if tag based on the current URL value.

for example, if the current page's url is accounts/login/ then don't show a link, without passing a variable from the view.

I am not sure how I can write an {% if %} tag for this, is it possible?

like image 262
bash- Avatar asked Sep 18 '11 15:09

bash-


People also ask

How will Django match URLs?

Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL, matching against path_info . Once one of the URL patterns matches, Django imports and calls the given view, which is a Python function (or a class-based view).

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What does form {% url %} do?

{% url 'contact-form' %} is a way to add a link to another one of your pages in the template. url tells the template to look in the URLs.py file. The thing in the quotes to the right, in this case contact-form , tells the template to look for something with name=contact-form .


2 Answers

You can also do this for dynamic urls using:

{% url 'show_user_page' user=user as the_url %} {% if request.get_full_path == the_url %}something{% endif %} 

where your urls.py contains something like:

(r'^myapp/user/(?P<user>\d+)/$', 'show_user_page'), 

I know this because I just spent ages drafting a stackoverflow question, when I found the answer in the docs.

I'd say even in simple cases this might be the better approach, because it is more loosely coupled.

like image 178
nimasmi Avatar answered Sep 20 '22 16:09

nimasmi


If you pass the "request" object to your template, then you are able to use this:

{% if request.get_full_path == "/account/login/" %} 
like image 30
Gabriel Ross Avatar answered Sep 18 '22 16:09

Gabriel Ross