我是 Django Web 开发的初学者。我注意到locals()
使用函数代替我习惯看到的上下文字典。
据我在网上看到的locals()
非常有用,那么是否有任何特殊情况,这不是真的,最好使用context_dictionary
?
Using locals()
在该教程中只是为了方便,因为他需要传递给模板的所有数据都存储在局部变量中。locals()
返回一个包含局部变量名称(作为键)和当前值(作为值)的字典。
您需要使用显式 context_dictionary,而不是传递locals()
,如果您必须构建数据并且在单独的变量中没有此类数据。
both locals()
context_dictionary 是字典,这是唯一的要求:一个类似字典的对象(即支持__getitem__(key)
and get(key, default=None)
方法)。如何获取词典取决于您。没有这方面的实践,但替代方案是:
- 返回一个
RequestContext()
,这是一个类似字典的对象,如果你使用CONTEXT_PROCESSORS
.
- Return
locals()
如果您的局部变量中有数据。
- 否则,请返回带有您的数据的手工字典。
EDIT- 例子:
自己构建字典的示例:
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 是 - 在任何一种情况下:
<html>
<body>
You are {{ full_name }} ({{ username }})
</body>
</html>
你会得到预期的结果。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)