Django将变量从基于类的视图传递给模板 [英] Django passing variables to templates from class based views

查看:34
本文介绍了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 中,我如何访问 var1var2?据我了解,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.var1self.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))

注意:render_to_response() 在 Django 3.0 及以上版本中被移除(使用 render() 代替).

Note: render_to_response() is removed in Django 3.0 and above (use render() instead).

另外,我不确定将 locals() 作为上下文传递给模板是否是一个好习惯.我更喜欢明确地构造传递给模板的数据 = 只传递模板中你真正需要的数据.

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.

这篇关于Django将变量从基于类的视图传递给模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆