Django将变量传递给基于类的视图的模板
如果我有一个基于类的视图,像这样,
If I have a class based view, like this,
class SomeView (View):
response_template='some_template.html'
var1 = 0
var2 = 1
def get(self, request, *args, **kwargs):
return render_to_response(self.response_template, locals(), context_instance=RequestContext(request))
我的问题是, some_template.html
,如何访问 var1
和 var2
?根据我的理解, locals()
排序只是将所有的局部变量转储到模板,这到目前为止工作非常好。但这些其他变量在技术上不是本地的,他们是一个类的一部分,所以我如何将它们传递?
My question is, inside the template some_template.html
, how do I access var1
and var2
? As far as I understood this, the locals()
sort of just dumps all the local variables into the template, which has worked very well so far. But these other variables aren't technically "local", they're part of a class, so how do I pass them over??
谢谢!
添加 self.var1
和 .var2
添加到 get
方法中的上下文中:
Add self.var1
and self.var2
to the context in get
method:
class SomeView (View):
response_template='some_template.html'
var1 = 0
var2 = 1
def get(self, request, *args, **kwargs):
context = locals()
context['var1'] = self.var1
context['var2'] = self.var2
return render_to_response(self.response_template, context, context_instance=RequestContext(request))
通过 locals()
作为模板的上下文是一个好的做法。我更喜欢构造传递到模板中的数据explicit =只传递你真正需要的模板。
Also, I'm not sure that passing locals()
as a context to the template is a good practice. I prefer to construct the data passed into the template explicitly = pass only what you really need in the template.
希望有帮助。