Django base.html中的动态变量 [英] Dynamic variables in Django base.html
问题描述
我有一个使用平面和不带request
对象的其他构造的应用程序.这会导致base.html中出现问题.这是一个简单的例子.
I have an app that uses flatpages and other constructs that don't take a request
object. This causes problems in base.html. Here's a simple example.
如果我想要类似"Welcome {{request.user.username}}!"之类的东西!在每个页面的顶部,实现此目标的最佳方法是什么?
If I wanted something like "Welcome {{ request.user.username }}!" at the top of every page, what's the best way to make that happen?
推荐答案
在 RequestContext 的更多信息.可以说,您应该能够编写一个上下文处理器,将request.user添加到每个模板的上下文中.像这样:
Flatpages use RequestContext
in rendering templates. Here's a bit more about RequestContext. Suffice to say, you should be able to write a Context Processor to add request.user to the context of every template. Something like this:
def user(request):
"""A context processor that adds the user to template context"""
return {
'user': request.user
}
然后将其添加到settings.py中的现有TEMPLATE_CONTEXT_PROCESSORS
:
Which you would then add to your existing TEMPLATE_CONTEXT_PROCESSORS
in settings.py:
TEMPLATE_CONTEXT_PROCESSORS = TEMPLATE_CONTEXT_PROCESSORS + (
'context_processors.user',
)
您只需要确保所有视图也将RequestContext
绑定到其模板:
You just need to make sure all your views bind RequestContext
to their templates as well:
return render_to_response('my_template.html',
my_data_dictionary,
context_instance=RequestContext(request))
这是一个很好的阅读在上下文处理器上.它们是非常有用的功能.
Here's a good read on Context Processors. They're a very helpful feature.
这篇关于Django base.html中的动态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!