我正在阅读 django 的权威指南,并且在第 4 章关于模板继承。似乎我没有做一些尽可能优雅的事情,因为我不得不复制一些代码以在调用 subview 时出现上下文。这是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 行,则该变量应出现的位置为空白。
最佳答案
您可以使用 Context Processor 将变量传递给每个模板。 :
1. 将上下文处理器添加到您的设置文件
首先,您需要将您的自定义上下文处理器添加到您的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
中包含的内容),但这是任意的。您可以选择您喜欢的任何函数名称。2. 创建上下文处理器
# 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
)
3. 将额外的上下文添加到您的 View 中
最后一步是使用
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))
关于django模板继承和上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3722174/