我正在阅读《Django权威指南》第四章关于模板继承的部分。似乎我没有按照最优雅的方式进行操作,因为我需要复制一些代码来使上下文在调用子视图时出现。以下是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())
每个函数中都包含当前日期行似乎是多余的。
这是主页调用的基本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行,那么变量应该出现的地方为空白。