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?
CodePudding user response:
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'