Django使用locals()

Mar*_*sov 4 python django

我是Django的网络开发初学者.我注意到使用了该locals()函数而不是我以前看到的上下文字典.

从我在互联网上看到的locals()内容非常有用,所以有什么特殊情况不是这样,使用它更好context_dictionary吗?

Lui*_*lli 12

使用locals()该教程仅仅是为了方便,因为所有他需要传递到模板中的数据被存储在本地变量.locals()返回一个包含局部变量名称(作为键)和当前值(作为值)的字典.

locals()如果必须构建数据并且在单独的变量中没有这样的数据,则需要使用显式的context_dictionary,而不是传递.

both locals()和context_dictionary都是字典,这是唯一的要求:类似字典的对象(即支持对象__getitem__(key)get(key, default=None)方法).如何获得字典,取决于你.没有这方面的做法,但替代方案是:

  • RequestContext()如果你使用的话,返回a ,这是一个类似dict的对象CONTEXT_PROCESSORS.
  • locals()如果您的局部变量中包含数据,则返回.
  • 否则,请返回包含数据的手工字典.

编辑 - 示例:

有关自行构建字典的示例:

def my_view(request):
    return render_to_response('hello.html', {
        'full_name': u"%s %s" % (request.user.first_name, request.user.last_name),
        'username': request.user.username
    })
Run Code Online (Sandbox Code Playgroud)

locals()以下构建字典的示例:

def my_view(request):
    full_name = u"%s %s" % (request.user.first_name, request.user.last_name)
    username = request.user.username

    return render_to_response('hello.html', locals())
Run Code Online (Sandbox Code Playgroud)

假设hello.html是 - 在任何一种情况下:

<html>
    <body>
        You are {{ full_name }} ({{ username }})
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

你会得到预期的结果.