0
votes

Here is the relevant template tag and html:

from django import template
from django.conf import settings

register = template.Library()


@register.inclusion_tag('auth_backend/templatetags/extends_layout.html')
def extends_layout():
    layout_template = getattr(settings, 'AUTHBACKEND_LAYOUT_TEMPLATE', '')
    return {'layout': layout_template}


{% if layout %}
  {% extends layout %} <<<<<<<<<<<<< Problem here
{% endif %}

When I use it in a view, I get the following error:

{# Sample view #}
{% load auth_backend_tags %}
{% load staticfiles %}

{% extends_layout %}

Django: Invalid block tag: 'endif'

If I delete {% extends layout %} then the error goes away, except my template tag is now blank.

What am I doing wrong?

1

1 Answers

3
votes

It's not possible to put the extends tag in an if statement. From the docs on template inheritance:

If you use {% extends %} in a template, it must be the first template tag in that template. Template inheritance won’t work, otherwise.

You might be able to achieve what you want by using a variable with the extends tag, instead of an inclusion tag. You can set the variable in your view, or using a context processor.

def my_view(request):
    extends = getattr(settings, 'AUTHBACKEND_LAYOUT_TEMPLATE', 'default_base.html')
    return render(request, 'my_template.html', {'extends': extends })

Then in your my_template.html:

{% extends extends %}