Django扩展base.html及其上下文



我在上下文中从views.py文件向base.html传递了一个变量。我已经将这个base.html扩展到另外几个模板。该变量仅在base.html中可见,而在任何其他扩展模板中都不可见。

如果我将相同的上下文传递给每个templates views.py文件,它确实有效。

当我扩展基时,它不应该也扩展变量吗?有没有其他方法可以让它发挥作用,或者我错过了什么?

当您扩展模板时,它会继承html代码。上下文需要始终由视图注入。如果希望始终传递相同的上下文,则需要对视图进行子类化,而不是模板。你可以写一个混音:

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

然后,当您需要相同的上下文时,可以使用继承:

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'

如果你想在子类中扩展上下文,你可以重写get_context_data(记得调用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

最新更新