Jaap Joris Vens
Jaap Joris Vens

Reputation: 3560

Why does Django give this error: Invalid block tag on line 3: 'else'

I have the following Django template:

{% if request.is_ajax %}
  {% extends "ajax.html" %}
{% else %}
  {% extends "base.html" %}
{% endif %}

When I render it I get the following error:

Invalid block tag on line 3: 'else'. Did you forget to register or load this tag?

Why am I getting this error?

Upvotes: 1

Views: 321

Answers (1)

tim-mccurrach
tim-mccurrach

Reputation: 6835

The {% extends %} tag has to be the first line in your template if you are to use it at all. It is invalid syntax to do otherwise. You can however use a variable. I would do the following:

def my_view(request):
    if request.is_ajax():
        base_template = "ajax.html"
    else:
        base_template = "base.html"
    ...
    context["base_template"] = base_template
    return render(request, "template.html", context)

Then in your template

{% extends base_template %}
...

An alternative approach if you don't want to add that logic to your view is to do the following:

{% extends request.is_ajax|yesno:"ajax.html,base.html" %}
...

Upvotes: 4

Related Questions