我在views.py
中有一个功能,例如:
def get_base_content():
footer = SiteContent.objects.get(pk=1)
return {
"footer" : footer,
}
我如何在template
中调用此函数并在其中使用footer
变量?
答案 0 :(得分:2)
如果您希望在所有模板上显示此变量,则需要实现template context processor。
您只需对代码进行最少的更改:
def get_base_content(request):
footer = SiteContent.objects.get(pk=1)
return {"footer" : footer}
现在,将其添加到单独的文件中,将其命名为custom_context.py
。在settings.py
中将其添加到TEMPLATE_CONTEXT_PROCESSORS
设置:
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages",
"myapp.custom_context.get_base_content", # don't forget the comma!
)
现在,在您的视图代码中,您只需确保使用RequestContext
。最简单的方法是使用render
shortcut:
from django.shortcuts import render
def myview(request):
return render(request,'hello.html',{'foo': 'bar'})
在hello.html
中,您将拥有{{ foo }}
和{{ footer }}
答案 1 :(得分:1)
您需要创建模板标记,根据您的情况,您可能需要查看inclusion tag。