Search code examples
djangodjango-templatestemplate-inheritance

Django: Extend template by return value of template tag


In a template, I want to determine the parent template of a sub template via the return value of a template tag.

This is the template tag. It returns the app label (the package name) and appends the corresponding template name to be extended:

{% app_label request.path %}

Now what I want to do is this:

{% extends app_label %}

Is this possible?


Solution

  • That's not possible. The {% extends %} tag needs to be the first template tag in a template (source):

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

    That means you can't have another template tag in front of it to construct a variable with the template's name.

    However, you could call the template tag function (perhaps after some refactoring) in the view and add the variable to the template context. It's then a normal variable that you can use in the {% extends ... %}tag.