我正在阅读django权威指南,并在第4章中介绍了模板继承。看起来,我没有做尽可能优雅的事情,因为我不得不复制一些代码,以便在调用子视图时显示上下文。这里是views.py中的代码:django模板继承和上下文
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线该变量应该显示为空白。