最近在学习Django,打算玩玩网页后台方面的东西,因为一直很好奇但却没怎么接触过。Django对我来说是一个全新的内容,思路想来也是全新的,或许并不能写得很明白,所以大家就凑合着看吧~
本篇笔记(其实我的所有笔记都是),并不会过于详细的讲解。因此如果有大家看不明白的地方,欢迎在我正版博客下留言,有时间的时候我很愿意来这里与大家探讨问题。(当然,不能是简简单单就可以百度到的问题-.-)
我所选用的教材是《The Django Book 2.0》,本节是第九章,模板高级进阶。
本节书中内容仅是参考,更多是按照文档中内容来介绍。
主要是因为书中版本过时,很多代码恰好是1.8中更新的内容,因此只得直接看文档了。
0. 目录
1. RequestContext函数和context处理器
1. RequestContext函数和context处理器
首先,我们回顾模板的视图函数如何书写:
from django.shortcuts import render_to_response def diary(request): return render_to_response('diary.html', {'name': 'qiqi'})
为了说明方便,我们同时给出另一种写法:
from django.http import HttpResponse from django.template import loader, Context def diary(request): t = loader.get_template('diary.html') c = Context({'name': 'qiqi'}) return HttpResponse(t.render(c))
或许还是有同学看不懂,那我就再给出第三种最笨的等价写法,大家大可略过直接往后看:
from django.http import HttpResponse from django.template import Template, Context def diary(request): tin = open('./templates/diary.html') html = tin.read() tin.close() inf = {'name': 'qiqi'} t = Template(html) c = Context(inf) return HttpResponse(t.render(c))