Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I Extend My Template Based on a Condition -Django

I have a template that needs to use separate base templates depending on whether a user is a system admin or a regular administrator. The main difference between the two templates is that one contains more nav bar items and links to other portions of the app. I’d like the system to recognize whether a user is a system admin or regular admin and extend the correct base template off of that test.

I know this can be accomplished by creating a second template and doing something like this in the views.py file:

if sysAdmin == True:
        template = loader.get_template('app/template1.html')
else:
        template = loader.get_template('app/template2.html')

There are multiple shared views between the two user groups and I would rather not have 4 sets of templates that are almost completely identical. I’d prefer to do something like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{% if sysAdmin == True %}
    {% extends "app/sysAdminBase.html" %}
{% elif sysAdmin == False %}
    {% extends "app/adminbase.html" %}
{% end if %}

However, this throws the error Invalid block tag on line 3: 'elif'. Did you forget to register or load this tag? Is this possible or will I need to create duplicate templates? Thank you

>Solution :

The extends tag can be passed a variable that resolves to a string, pass the template that you want to extend in your context

if sysAdmin == True:
    context['parent_template'] = 'app/sysAdminBase.html'
else:
    context['parent_template'] = 'app/adminbase.html'

Template:

{% extends parent_template %}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading