[Answered ]-Django: Extend template by return value of template tag

1👍

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.

1👍

I solved the problem with a context processor:

def app_label_processor(request):
    return {
        'app_base_template': resolve(request.path).app_name
    }

Then I can use this:

{% extends app_base_template %}

All you need to do is

  • adding your app urls as described in this answer
  • adding your context processor to settings.TEMPLATE_CONTEXT_PROCESSORS
  • use RequestContext for rendering the template.
👤Martin

Leave a comment