简体   繁体   English

从模板到视图的Django变量 - 最佳实践

[英]Django variables from templates to views - best practice

I realize that using: 我意识到使用:

...
return render_to_response('mytemplate.html',
locals(), context_instance=RequestContext(request))

in views is not considered good code and something like: 在视图中不被视为良好的代码,如:

...
return render_to_response('mytemplate.html', {
        'some_variable' : some_variable,
        'some_list': some_list,
}, context_instance=RequestContext(request)) 

is considered better for its legibility and explicitness. 因其易读性和明确性而被认为更好。 I was just curious how best to deal with variables which may or may not be returned. 我只是好奇如何处理可能会或可能不会返回的变量。 Should I explicitly set them in the views like this: 我应该在这样的视图中明确设置它们:

...
some_variable = None
some_variable = <some business logic>
return render_to_response('mytemplate.html', {
        'some_variable' : some_variable,
        'some_list': some_list,
}, context_instance=RequestContext(request)) 

which would result in more lengthy view code. 这将导致更长的视图代码。 Or should I check for existence of the variables before including them in the response? 或者我应该在将变量包含在响应中之前检查变量是否存在?

Of course if I do nothing then I get: 当然,如果我什么都不做,那么我得到:

local variable 'some_variable' referenced before assignment

Any suggestions welcomed. 欢迎任何建议。

A middle way is to use the context dictionary itself as a stack. 中间方法是将上下文字典本身用作堆栈。

context = {}
if <condition>:
    context['cond1'] = 'foo'

if <condition2>:
    context['cond2'] = 'bar'

return render_to_response('template.html', context)

(Also note that since Django 1.3 you can use render(request, template, context) instead of the longwinded context_instance=RequestContext stuff.) (另请注意,从Django 1.3开始,您可以使用render(request, template, context)而不是longwinded context_instance=RequestContext 。)

Either build your context conditionally, ie: 要么有条件地构建你的上下文,即:

context = { 'some_list': some_list }

...

if <something>:
    context['some_variable'] = some_variable

...

return render_to_response('mytemplate.html', context, context_instance=RequestContext(request)    

Or use sensible defaults: 或使用合理的默认值:

return render_to_response('mytemplate.html', {
    'some_variable' : some_variable or 'Default',
    'some_list': some_list,
}, context_instance=RequestContext(request))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM