【django】django render()和render_to_response()和direct_to_template()和locals()

转载自:https://www.douban.com/note/278152737/

 

前两者区别stackoverflow给了较明确的答案

参考网址:http://stackoverflow.com/questions/5154358/django-what-is-the-difference-between-render-render-to-response-and-direc

 

自django1.3开始:render()方法是render_to_response的一个崭新的快捷方式,前者会自动使用RequestContext。而后者必须coding出来,这是最明显的区别,当然前者更简洁。

 

    return render_to_response('blog_add.html',{'blog': blog, 'form': form, 'id': id, 'tag': tag},

                              context_instance=RequestContext(request))

 

    return render(request, 'blog_add.html', {'blog': blog, 'form': form, 'id': id, 'tag': tag})

 

stackoverflow里还给了return direct_to_template(request, template_name, my_data_dictionary)这样一个例子,关于其解释:

     direct_to_template() is designed to be used just in urls.py without a view defined in views.py but it can be used in views.py to avoid having to type RequestContext.

     direct_to_template is something different. It's a generic view that uses a data dictionary to render the html without the need of the views.py, you use it in urls.py. 

 

direct_to_template()还没用到过,不再赘述,留下此方法,备用

 

locals()用法:locals()可以直接将函数中所有的变量全部传给模板。当然这可能会传递一些多余的参数,有点浪费内存的嫌疑,对可读性有影响,不推荐。

    return render(request, 'blog_add.html',locals())

 

那么长一段代码精简到三分之一的长度。有种爽歪歪的感觉!feel well !

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值