[英]Django about get_context_data()
我在看Django源代碼以了解super(ExampleView, self).get_context_data(**kwargs)
以及為什么在我的視圖中使用它:
class ExampleView(TemplateView):
# ... atributes
def get_context_data(self, **kwargs):
context = super(ExampleView, self).get_context_data(**kwargs)
context['key'] = 'value'
return context
我發現:
class ContextMixin(object):
"""
A default context mixin that passes the keyword arguments received by
get_context_data as the template context.
"""
def get_context_data(self, **kwargs):
if 'view' not in kwargs:
kwargs['view'] = self
return kwargs
我無法弄清楚那個條件或kwargs['view'] = self
是做什么的。
我曾嘗試在沒有該默認條件的情況下覆蓋get_context_data()
:
class ExampleView(TemplateView):
# .. atributes
def get_context_data(self, **kwargs):
kwargs['key'] = 'value'
return kwargs
它的工作方式與我編寫的第一個代碼相同。
如果尚不存在,那兩行代碼會將視圖作為變量添加到上下文中。 大多數人從不使用此功能,但是您可以執行以下操作:
class SomeView(TemplateView):
template_name = "something.html"
title = "My list of books"
def books(self): #custom method
return Book.objects.all()
然后,您可以在模板中通過view變量引用books方法和title屬性:
<h1>{{ view.title }}</h1>
<ul>
{% for book in view.books %}
<li>{{ book }}</li>
{% enfor %}
<ul>
是的,請注意,在這種情況下,您甚至不需要自定義的get_context_data()方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.