问题描述
我是使用Django进行Web开发的初学者.我已经注意到,使用的是 locals()
函数,而不是我经常看到的上下文字典.
I am beginner in web development with Django. I have noticed that the locals()
function is used instead of the context dictionary that I am used to see.
从我在互联网上看到的内容来看, locals()
很有用,那么是否有任何特殊情况会导致错误,并且最好使用 context_dictionary
?
From what I see on the internet locals()
is pretty useful, so are there any special cases where this is not true and its better to use the context_dictionary
?
推荐答案
使用 locals()
只是为了方便,因为他需要传递给模板的所有数据都存储在局部变量. locals()
返回一个包含本地变量名称(作为键)和当前值(作为值)的字典.
Using locals()
in that tutorial is just for convenience, since all the data he needs to pass to the template is stored in local variables. locals()
returns a dictionary holding the local variables names (as keys) and the current values (as values).
如果必须构建数据并且没有单独的变量中的数据,则需要使用显式的context_dictionary,而不是传递 locals()
.
You need to use an explicit context_dictionary, instead of passing locals()
, if you must build your data and you don't have such data in separate variables.
locals()
和context_dictionary都是字典,这是唯一的要求:类字典对象(即支持 __ getitem __(key)
和的对象)get(key,default = None)
方法).如何获得字典,取决于您.对此没有任何实践,但是替代方法是:
both locals()
and context_dictionary are dictionaries, and that's the only requirement: a dictionary-like object (i.e. an object supporting __getitem__(key)
and get(key, default=None)
methods). How you get the dictionary, is up to you. There's no practice about that, but alternatives are:
- 如果使用
CONTEXT_PROCESSORS
,则返回一个类似dict的对象RequestContext()
. - 如果您的本地变量中包含数据,请返回
locals()
. - 否则将返回带有数据的手工字典.
- Return a
RequestContext()
, which is a dict-like object, if you useCONTEXT_PROCESSORS
. - Return
locals()
if you have the data in your local variables. - Return a hand-made dictionary with your data otherwise.
编辑-示例:
有关自行构建词典的示例:
Example on building the dictionary on your own:
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是-在任何一种情况下:
Assume hello.html is - in either case:
<html>
<body>
You are {{ full_name }} ({{ username }})
</body>
</html>
您将获得预期的结果.
这篇关于Django使用locals()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!