How do I inherit from different templates in Djanog based on whether the user is logged in or not

45 views Asked by At

Exactly what the question says. I have three templates base.html, logged_in_base.html, and page.html. I want page.html to extend base.html when the user isn't logged in and to extend logged_in_base.html when the user is logged in. How do I do this?

(This is basically because I have a different navbar for logged in users and not logged in users.)

1

There are 1 answers

3
dgw On

Since {% extends %} needs to be the first statement in a template, one cannot put the logic in the template.

But one can put the logic in the view since {% extends %} can work with a variable:

views.py

def page(request):
    base_template = 'logged_in_base.html' if request.user.is_authenticated else 'base.html'
    return render(request, 'page.html',
                  {'base_template': base_template})

page.html

{% extends base_template %}
<!-- Now put your content here -->

An alternative solution could be a single base template and conditional statement to decide which navigation bar to use.

{% if user.is_authenticated %}
    <!-- Navbar Logged in -->
{% else %}
    <!-- Navbar anonymous user -->
{% endif %}