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?
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).
{% %} 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.
{% 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 .
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.
If you pass the "request" object to your template, then you are able to use this:
{% if request.get_full_path == "/account/login/" %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With