Writing your own context processors
有隻有兩個規則是有...
- 只有一個參數就是
request
- 必須返回字典
context_processors.py
def database_social_links(request):
social_links = SocialLinks.objects.all()
return {'social_links': social_links }
更新您的settings.py遵循
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
# insert your TEMPLATE_DIRS here
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
# Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
'your_app.context_processors.database_social_links',
# list if you haven't customized them:
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
],
},
},
]
而在你的base.html文件或任何...
{% for links in social_links %}
{{ link.name }} {{ link.font_awesome }}
{% endfor %}
謝謝您的回答拉賈!所以你說我不需要通過「views.py」傳遞這些數據? – Captain
是的,沒錯。查看自定義上下文處理器的概念是在未提及的情況下執行視圖時向數據定義的字典注入。這樣可以在每個模板中使用。 –
但是你從數據庫中檢索它,所以要小心這個縮放和所有的東西。每頁請求都會從數據庫獲取值,如果你問我,我最好避免這種情況。相反,我會使用redis像數據庫更好地獲得... :) –