在该教程中使用locals()只是为了方便,因为他需要传递给模板的所有数据都存储在局部变量中. locals()返回一个包含局部变量名称(作为键)和当前值(作为值)的字典.
如果必须构建数据并且在单独的变量中没有这样的数据,则需要使用显式的context_dictionary,而不是传递locals().
locals()和context_dictionary都是字典,这是唯一的要求:类字典对象(即支持__getitem __(key)和get(key,default = None)方法的对象).如何获得字典,取决于你.没有这方面的做法,但替代方案是:
>如果使用CONTEXT_PROCESSORS,则返回RequestContext(),它是一个类似dict的对象.
>如果您的局部变量中包含数据,则返回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
})
从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())
假设hello.html是 – 在任何一种情况下:
You are {{ full_name }} ({{ username }})
你会得到预期的结果.