如何使某些东西出现在Django的每个页面上? [英] How to get something to appear on every page in Django?

查看:38
本文介绍了如何使某些东西出现在Django的每个页面上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇在每页或多页上显示某些内容的最佳实践方式,而不必像这样将数据手动分配给每一页:

I'm curious as to the best-practise way to handle having something appear on every page, or on a number of pages without having to assign the data manually to every page like so:

# 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 分配...我只是不确定执行此操作的最佳方法.我很确定那不是最后一个.

Now I can think of a few ways to do this, including writing my own Context or maybe some middleware, and of course, copy/pasting this locality assignment on every page... I'm just not sure of the best way to do this. I'm pretty sure that it's not that last one though.

推荐答案

您想要一个

You want a context processor. The data they generate is included in every context created as a RequestContext. They are perfect for this.

结合显示通用内容的基本模板,您可以摆脱对复制和粘贴代码的大量需求.

Combined with base templates that show common things, you can get rid of lots of need for copying and pasting code.

这篇关于如何使某些东西出现在Django的每个页面上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆