python的render参数_<django中render_to_response的可选参数和使用方法>

在django官方文档中有比较详细的介绍,在此我按照自己的理解适当的阐述一下:

returnrender_to_response(①'my_template.html',

②my_data_dictionary,

③context_instance=RequestContext(request)

)

①template_name

毫无疑问这个就是你要渲染的模板的路径下的模板名,(一个.html文件),注意:这个参数是必须要求有的,假如没有的话是会报错的。

(官方文档阐述:The full name of a template to use or sequence of template names. If a sequence is given, the first templa

te that exists will be used)

②my_data_dictionary

这是一个字典(python dict),字典中的值添加到模板上下文,默认情况下这个字典是空的,如果调用这个模板中的值,你的模板将会

被视图函数渲染。

③context_instance=RequestContext(request)在使用render_to_response,render_to_string等shortcut的时候,可以附带context_instance参数

来使用RequestContext:

def some_view(request):

... return render_to_response('my_template.html',

my_data_dictionary, context_instance=RequestContext(request))

或者

def view(request):

#...

return render_to_response('template1.html',

{'message':'I am the view.'},

context_instance=RequestContext(request,processors=[custom_proc]))

其中custom_proc为自定义变量的视图,当然也可以在TEMPLATE_CONEXT_PROCESSORS中直接定义一个可

调用的函数元组,然后在processors中直接来使用。

由于加载模板、填充 context 、将经解析的模板结果返回为 HttpResponse 对象这一系列操

作实在太常用了,Django 提供了一条仅用一行代码就完成所有这些工作的捷径。该捷径就是

位于 django.shortcuts 模块中名为 render_to_response() 的函数。大多数时候,你将使

用 render_to_response() ,而不是手动加载模板、创建 Context 和 HttpResponse 对象。

下面就是使用 render_to_response() 重新编写过的 current_datetime 范例。

from django.shortcuts import render_to_response

import datetime

def current_datetime(request):

now = datetime.datetime.now()

return render_to_response('current_datetime.html', {'current_date': now})

大变样了!让我们逐句看看代码发生的变化:我们不再需要导入 get_template 、 Template 、 Context 和

HttpResponse 。相反, 我们导入 django.shortcuts.render_to_response 。import

datetime 继续保留

.在 current_datetime 函数中,我们仍然进行 now 计算,但模板加载、上下文创建、模板解析和

HttpResponse

创建工作均在对 render_to_response() 的调用中完成了。由于

render_to_response()

返回 HttpResponse

对象,因此我们仅需在视图中return 该值。

render_to_response() 的第一个参数必须是要使用的模板名称。如果要给定第二个参数,那么该参数

必须是为该模板创建 Context 时所使用的字典。如果不提供第二个参数,render_to_response() 使用一个空字典。

只有你使用了render_to_response之后,你就不用使用Django模板系统的基本规则: 写模板,创建 Template 对象,创建 Context , 调用 render() 方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值