开发者

Dynamic variables in Django 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.

If I wanted something lik开发者_高级运维e "Welcome {{ request.user.username }}!" at the top of every page, what's the best way to make that happen?


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
    }

Which you would then add to your existing TEMPLATE_CONTEXT_PROCESSORS in settings.py:

TEMPLATE_CONTEXT_PROCESSORS = TEMPLATE_CONTEXT_PROCESSORS + (
    'context_processors.user',
)

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.


Context processors.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜