我正在阅读django的权威指南,我在第4章中介绍了模板继承。似乎我没有做一些尽可能优雅的事情,因为我必须复制一些代码,以便在调用子视图时显示上下文。这是views.py中的代码:
def homepage(request):
current_date = datetime.datetime.now()
current_section = 'Temporary Home Page'
return render_to_response("base.html", locals())
def contact(request):
current_date = datetime.datetime.now()
current_section = 'Contact page'
return render_to_response("contact.html", locals())
在每个函数中包含current_date行似乎是多余的。
以下是主页调用的基本html文件:
<html lang= "en">
<head>
<title>{% block title %}Home Page{% endblock %}</title>
</head>
<body>
<h1>The Site</h1>
{% block content %}
<p> The Current section is {{ current_section }}.</p>
{% endblock %}
{% block footer %}
<p>The current time is {{ current_date }}</p>
{% endblock %}
</body>
</html>
和子模板文件:
{% extends "base.html" %}
{% block title %}Contact{% endblock %}
{% block content %}
<p>Contact information goes here...</p>
<p>You are in the section {{ current_section }}</p>
{% endblock %}
如果在调用子文件时没有包含current_date行,那么该变量应该出现在哪里。
答案 0 :(得分:16)
您可以使用Context Processor:
将变量传递给每个模板首先,您需要将自定义上下文处理器添加到settings.py
:
# settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
'myapp.context_processors.default', # add this line
'django.core.context_processors.auth',
)
由此您可以得出,您需要创建一个名为context_processors.py
的模块并将其放在应用程序的文件夹中。您可以进一步看到它需要声明一个名为default
的函数(就像我们在settings.py
中所包含的那样),但这是任意的。您可以选择自己喜欢的功能名称。
# context_processors.py
from datetime import datetime
from django.conf import settings # this is a good example of extra
# context you might need across templates
def default(request):
# you can declare any variable that you would like and pass
# them as a dictionary to be added to each template's context:
return dict(
example = "This is an example string.",
current_date = datetime.now(),
MEDIA_URL = settings.MEDIA_URL, # just for the sake of example
)
最后一步是使用RequestContext()
处理其他上下文,并将其作为变量传递给模板。下面是一个非常简单的示例,说明了对views.py
文件的修改类型:
# old views.py
def homepage(request):
current_date = datetime.datetime.now()
current_section = 'Temporary Home Page'
return render_to_response("base.html", locals())
def contact(request):
current_date = datetime.datetime.now()
current_section = 'Contact page'
return render_to_response("contact.html", locals())
# new views.py
from django.template import RequestContext
def homepage(request):
current_section = 'Temporary Home Page'
return render_to_response("base.html", locals(),
context_instance=RequestContext(request))
def contact(request):
current_section = 'Contact page'
return render_to_response("contact.html", locals(),
context_instance=RequestContext(request))
答案 1 :(得分:3)
因此,您可以使用django.views,generic.simple.direct_to_template而不是render_to_response。它使用RequestContext internaly。
from django.views,generic.simple import direct_to_template
def homepage(request):
return direct_to_template(request,"base.html",{
'current_section':'Temporary Home Page'
})
def contact(request):
return direct_to_template(request,"contact.html",{
'current_section':'Contact Page'
})
或者你甚至可以直接在urls.py上指定它,例如
urlpatterns = patterns('django.views.generic.simple',
(r'^/home/$','direct_to_template',{
'template':'base.html'
'extra_context':{'current_section':'Temporary Home Page'},
}),
(r'^/contact/$','direct_to_template',{
'template':'contact.html'
'extra_context':{'current_section':'Contact page'},
}),
答案 2 :(得分:1)
对于django v1.8 +可以访问context processor内返回的变量。
TEMPLATES
settings.py
列表中
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'your_app.context_processor_file.func_name', # add this line
],
},
},
]
context_processor_file.py
def func_name(request):
test_var = "hi, this is a variable from context processor"
return {
"var_for_template" : test_var,
}
var_for_template
例如,在此处添加以下内容: base.html
<h1>{{ var_for_template }}</h1>
这将呈现:
<h1>hi, this is a variable from context processor</h1>
&#13;
将模板更新为django 1.8+,请点击this django doc