模版中的变量由context中的值来替换,如果在多个页面模版中含有相同的变量
比如:每个页面都需要{{user}},笨办法就是在每个页面的请求视图中都把user放到context中。
<span style="font-family:Microsoft YaHei;">from django.temlate import loader,Context
t = loader.get_template('xx.html')
c = Context({'user':'zhangsan'})
return HttpResponse(t.render(c)) #httpresponse</span>
也可以简写为:
<span style="font-family:Microsoft YaHei;">from django.short_cuts import render_to_response
render_to_response('xxx.html',{'user':'zhangsan'})</span>
但是这样写不好的地方是就是造成代码的冗余,不易维护
此时就可以用Context的一个子类:django.template.
RequestContext
在渲染模版的时候就不需要Context,转而使用RequestContext。
RequestConntext需要接受request和processors参数,processors是
context处理器的列表集合。
context处理器
<span style="font-family:Microsoft YaHei;">from django.template import RquestContext
def custom_pros(request): #context处理器
return {'age':22,'user':request.user}</span>
<span style="font-family:Microsoft YaHei;">#view 代码块
c = RequestContext(request,{'name':'zhang'},processors=[custom_pros])
return HttpResponse(t.render(c)) </span>
这样在每个试图中只需把custom_pros传递给RequestContext的参数processors就行了。
如果是render_to_response与RequestContext结合使用,那么render_to_response接收参数context_instance.
<span style="font-family:Microsoft YaHei;">render_to_response('xxx.html',{'name':'zhang'},context_instance=RequestContext(request,processors[custom_pros])
</span>
但是这样还是很麻烦,代码的冗余并没有真正解决,你不得不在试图函数中明确指定context处理器,为此,
Django提供了全局的context处理器。
全局context处理器
默认情况下,Django采用参数
TEMPLATE_CONTEXT_PROCESSORS指定默认处理器
意味着只要是调用的RequestContext,那么默认处理器中返回的对象都就将存储在context中。
template_context_processors默认在settings文件中是没有的,而是设置在global_settings.py文件中
如果想加上自己的context处理器,就必须在自己的settings.py中显示的指出参数:TEMPLATE_CONTEXT_PROCESSORS
默认:
<span style="font-family:Microsoft YaHei;">TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',#django1.4 or after
'django.core.context_processors.auth', #django1.4 before
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'myapp.processor.foos',
)</span>
或者是:
<span style="font-family:Microsoft YaHei;">from django.conf import global_settings
TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS +("myapp.processor.foos",)</span>
此时,在试图中只要把request参数传递给RequestContext就ok了。
<span style="font-family:Microsoft YaHei;">render_to_response('xxx.html',{'age':33},context_instance=RequestContext(request))</span>
系统在接受到该视图的请求时,自动执行处理器 “myapp.processor.foos",并把其返回值渲染到模版中。