5xum
5xum

Reputation: 5555

Chaining `if` and `url` template tags

I have a django page which contains a login form in the navbar (for quick login from the homepage) and a separate login page (to which the user is redirected if he mistypes).

My template structure is such that I have a base.html template and a navbar.html template. All of my pages extend the base.html template (after all, that's what it's there for, right?), and most (but not all) pages then include the navbar.html template inside. The code I paste below is from the navbar template.

I know this could be done more elegantly, but the question I have is more general, this is just a use case. What I want to do is, in the navbar, to only show the login form if the site shown at the moment is not the login site. Currently, I have

{% if not 'accounts/login' in request.get_full_path %}
<form class="navbar-form navbar-right" action="{% url 'auth_login' %}" method="POST">
    {% csrf_token %}
    <div class="form-group">
        <input class="form-control" name="username" type="text" placeholder="Username">
    </div>
    <div class="form-group">
        <input class="form-control" name="password" type="password" placeholder="Password">
    </div>
    <button class="btn btn-default" type="submit">Log in</button>
</form>
{% endif %}

Which works fine. However, I don't like the fact that the 'accounts/login' is hardcoded. Usually, I was taught that it was best practice to use the {% url 'auth_login %} to get the 'accounts/login' string as this allows the string to still be correct even if I change the URLConf. However, I cannot simply write

{% if url 'auth_login' in request.get_full_path %}

What I imagine would be best is to somehow set a context variable to the value of {% url 'auth_login' %}, but how could this be done as cleanly as possible?

Upvotes: 1

Views: 67

Answers (1)

Sayse
Sayse

Reputation: 43320

In your base form you can just add a block to your navigation that allows for a page to have extra navigation items

 {% block extra_nav %}{% endblock %}

then inside your login page you can include the login form

 {% block extra_nav %}{% include 'login_form' %}{% endblock %}    

Although this can get messy quickly.

Alternatively, you include an extra data parameter that you only ever pass in the pages that need to show it

 { 'show_login': True }


{% if show_login %}
     ... your form
{% endif %}

Since this will equate to false if not present, it will not be shown in areas where its not included

Upvotes: 1

Related Questions