如何在Django的每个页面上都显示一些内容?

2024-10-01 15:38:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我很想知道一种最佳的实践方法来处理在每一页或多页上出现的内容,而不必手动将数据分配到每一页,如下所示:

# 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)
    )

现在我可以想出一些方法来实现这一点,包括编写自己的上下文或者一些中间件,当然,在每个页面上复制/粘贴这个locality赋值。。。我只是不知道最好的办法。我很确定这不是最后一次。在


Tags: toinstancecoreindexreturnresponserequestdef
3条回答

你想要一个context processor。它们生成的数据包含在作为RequestContext创建的每个上下文中。它们非常适合这个。在

与显示常见内容的基本模板相结合,可以消除大量复制和粘贴代码的需要。在

中间件是一种选择,或者您可以编写一个自定义的template tag。在

在模板引擎中使用继承:

有一个基本.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>

然后在每个需要通用代码的页面中,只需:

^{pr2}$

http://docs.djangoproject.com/en/dev/topics/templates/#id1

这与上下文处理相结合将消除大量重复代码。在

相关问题 更多 >

    热门问题