Invalid block tag 'else'. Did you forget to register or load this tag?

Viewed 1458

Why I got this error? I have this error on django, while it's working correctly on Flask.

1   {% if user.is_authenticated %}
2     {% extends "home.html" %}
3   {% else %}
4     {% extends "index_not_auth.html" %}
5   {% endif %}

TemplateSyntaxError at / Invalid block tag on line 3: 'else'. Did you forget to register or load this tag? Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.2 Exception Type: TemplateSyntaxError Exception Value:
Invalid block tag on line 3: 'else'. Did you forget to register or load this tag? Exception Location: D:\GitHub Repositories\Django-WebApp\venv\lib\site-packages\django\template\base.py, line 534, in invalid_block_tag Python Executable: D:\GitHub Repositories\Django-WebApp\venv\Scripts\python.exe Python Version: 3.6.1

1 Answers

You cannot put the extends template tag in an if-else, there can only be one extends tag in a template and it must be at the start of the template. If you want to dynamically extend templates you should pass the template name in the context from the view and use that variable in the extends tag:

from django.shortcuts import render


def some_view(request):
    # ...
    context = {}
    if request.user.is_authenticated:
        context['parent_template'] = 'home.html'
    else:
        context['parent_template'] = 'index_not_auth.html'
    return render(request, 'some_template.html', context)

Now in the template:

{% extends parent_template %}
<!-- Rest of template -->
Related