问题描述
我很好奇在每页或多页上显示某些内容的最佳实践方式,而不必像这样将数据手动分配给每一页:
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.
推荐答案
您想要一个上下文处理器.它们生成的数据包含在每个以 RequestContext
创建的上下文中.他们是完美的.
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的每个页面上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!