[英]Django CBV - How to avoid repeating the get_context_data for every view just to get a custom title?
我正在為項目的每個頁面設置{{ title }}
。 有時,此title
是靜態字符串,例如Enter your Name
,有時它基於該頁面上的相關對象,例如Employee.first_name
。
要創建context['title']
,我在每個基於類的視圖中使用get_context_data
。 但這似乎導致我每次都重復一大堆代碼,而我正在尋求以某種方式減少它。
例如,為每個頁面編寫自定義標題,我必須寫這個:
def get_context_data(self, **kwargs):
context = super(SomeView, self).get_context_data(**kwargs)
context['title'] = 'Title for This page'
return context
我覺得擁有一個mixin是理想的,我不知何故只是傳遞了title
的變量,我的context
字典會根據傳入的變量自動添加context['title']
。
這可能嗎? 有沒有辦法創建一個mixin,這樣我所要做的就是傳入一個變量,它會給我一個僅用於標題的上下文,而不是為每個視圖寫出那塊代碼?
是的,這很容易:
class YourTitleMixin(object):
title = None # or your default title if you won't provide any
def get_title(self):
return self.title
def get_context_data(self, **kwargs):
context= super(YourTitleMixin, self).get_context_data(**kwargs)
context['title'] = self.get_title()
return context
你用它:
def YourPageView(YourTitleMixin, DetailView):
title = "Your Page Title" # you can either use this ...
def get_title(self):
return self.get_object().name # ... or that, if your title should be generated from some data
但這有必要嗎? 您是否只在模板中使用過一次標題? 你在視圖之間共享一個模板嗎? 也許你可以純粹在你的模板中做到這一點? 例如:
{# base.html #}
<html>
<head>
<title>{% block page_title %}My page{% endblock %}</title>
</head>
</html>
{# detail.html #}
{% extends "base.html" %}
{% block title %}{{ article.name }} - {{ block.super }}{% endblock %}
{# will result in "article name - My Page". You don't need to use super if you don't want to #}
我通常用mixin解決這個問題:
class TitleMixin(object):
"""Pass a defined title to context"""
title = None
def get_title(self):
return self.title
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['title'] = self.get_title()
return context
在您的視圖中,您可以執行以下操作:
class BlogIndex(TitleMixin, ListView):
title = 'Blog entries'
class EntryDetail(TitleMixin, DetailView)
def get_title(self): # for dynamic title, such as coming from a model field
return self.object.title
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.