Krystian Cybulski
Krystian Cybulski

Reputation: 11108

Can a django template find out its named url or can a base template know which template is extending it?

In my URLConf, I have my URLs neatly named so I can do reverse lookups and keep everything DRY.

All my templates extend a universal template named base.html. In base.html, amongst a lot of HTML framework, I display a login form.

I also have a specific view which uses Django's provided auth_views.login view, which displays my custom template login.html. This template, like all others, extend the base.html template.

In cases like this, I would like that the base.html template would not display its login form (the login.html template already is displaying a login form). In order to do this, base.html either needs to know that it is being used to extend login.html, or, know that the named URL which resulted in base.html being extended is has the name 'myapp-login'.

Can you suggest a way to do this? I am thinking of writing my own view which will call auth_views.login with extra context which includes a suppress_header_login_form var. Based on this var, the base.html template could suppress the login form. However, I am trying to see if there is a nicer way to accomplish this.

Upvotes: 1

Views: 315

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599610

You could manage this with template inheritance and blocks.

Your base.html defines a block called login, which surrounds the HTML for the login - and your login.html overrides that block with an empty version:

base.html:

{% block login %}
    ... login form here ...
{% endblock %}

{% block main %}
{% endblock %}

login.html:

{% extends "base.html" %}

{% block login %}
{% endblock %}

{% block main %}
   ... real login form here ...
{% endblock %}

Upvotes: 4

Related Questions