如何在Django中让某个内容在每页上显示?
我很好奇,如何才能让某个内容在每一页上都出现,或者在几页上出现,而不需要像这样手动在每一页上分配数据:
# views.py
def page0(request):
return render_to_response(
"core/index.html",
{
"locality": getCityForm(request.user),
},
context_instance=RequestContext(request)
)
def page1(request):
return render_to_response(
"core/index.html",
{
"locality": getCityForm(request.user),
},
context_instance=RequestContext(request)
)
...
def page9(request):
return render_to_response(
"core/index.html",
{
"locality": getCityForm(request.user),
},
context_instance=RequestContext(request)
)
我想到了一些方法,比如写自己的上下文(Context)或者使用一些中间件,当然,也可以在每一页上复制粘贴这个locality
的赋值……但我不太确定哪种方法最好。我很确定最后一种方法不是最佳选择。
3 个回答
0
为了实现你想要的功能,我会简单地定义一个函数:
def foobar(req):
return render_to_response(
"core/index.html",
{
"locality": getCityForm(req.user),
},
context_instance=RequestContext(req)
)
把这个函数放在一个叫 myfun
的模块里,然后在需要的地方用 return myfun.foobar(request)
来调用它。你可能还想加几个参数,但只要保持简单,这样做比定义中间件、使用面向对象编程等方式要简单得多。
4
在模板引擎中使用继承:
首先,创建一个 base.html 文件,这个文件里包含了大家都需要的公共代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<link rel="stylesheet" href="style.css" />
<title>{% block title %}My amazing site{% endblock %}</title>
</head>
<body>
<div id="sidebar">
{% block sidebar %}
<ul>
<li><a href="/">Home</a></li>
<li><a href="/blog/">Blog</a></li>
</ul>
{% endblock %}
</div>
<div id="content">
{% block content %}{% endblock %}
</div>
</body>
</html>
然后,在每个需要这些公共代码的页面中,只需简单地:
{% extends "base.html" %}
{% block title %}My amazing blog{% endblock %}
{% block content %}
{% for entry in blog_entries %}
<h2>{{ entry.title }}</h2>
<p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
http://docs.djangoproject.com/en/dev/topics/templates/#id1
这样结合上下文处理,就能减少很多重复的代码。
16
你需要一个上下文处理器。它们生成的数据会被包含在每个创建的RequestContext
中。这些处理器非常适合这个用途。
如果把它和一些基础模板结合使用,这些模板展示了一些常见的内容,你就可以省去很多复制和粘贴代码的麻烦。