Django base.html中的动态变量 [英] Dynamic variables in Django base.html

查看:79
本文介绍了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屋!

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