Django extend base.html along with its context

Viewed 164

I've passed a variable to base.html from my views.py file in a context. I've extended this base.html to another several templates. The variable is only visible in the base.html and not any other extended template.

It does work if I pass the same context to each templates views.py file.

As I extended the base, shouldn't it also extend the variable? Is there any other way to get this working, or am I missing something?

1 Answers

When you extend a template, it inherits the html code. The context needs to be always injected by the view. If you want to pass always the same context, you need to subclass the view and not the template. You can write a mixin:

class GetContextViewMixin:
    def get_context_data(self, *args, **kwargs):
       return ['foo': 'foo']  # Replace with the real context

Then when you need the same context, you can use inheritance:

from django.views.generic import TemplateView


# The template of this view will obtain its context from the mixin method
class ExampleView(GetContextViewMixin, TemplateView):
   template_name = 'foo.html'

If you want to extend the context in subclasses, you can override get_context_data (remember to call super):

from django.views.generic import TemplateView


class ExampleView2(GetContextViewMixin, TemplateView):
   template_name = 'foo2.html'
   
   def get_context_data(self, *args, **kwargs):
       context = super().get_context_data(*args, **kwargs)
       context['foo2'] = 'foo2'  # Extend the context
       return context
Related