django 学习 (二) 模板
1. 在應(yīng)用的目錄下創(chuàng)建templates目錄,并創(chuàng)建一個html文件,比如my.html
2. 修改應(yīng)用的views.py文件,將my.html文件反饋給請求,有以下幾種寫法
? ? ? ? ??
? ??? 1)?from django.template import loader, Context
?????????from django.http import HttpResponse
????????? def index(req)
? ? ? ? ? ? ? ? ?t = loader.get_template('my.html')
? ? ? ? ? ? ? ? ?c = Context({})
? ? ? ? ? ? ? ? ?return HttpResponse(t.render(c))
?????? 2) from django.template import loader, Context, Template
????????? def index(req)
??????????????? t = Template('<h1>{{hello}}</h1>')
??????????????? c = Context{{'hello':'zhang'}}
??????????????? return HttpResponse(t.render(c))
? ? ?? 3)?from django.shortcuts import render_to_response
?????????? def index(req)
? ? ? ? ? ? ? ? ?return render_to_response('my.html', {})
?????? 從前兩種方法可以看到使用模板的三個要素,模板文件,需要渲染的數(shù)據(jù),HttpResponse對象
?????? 使用第三種方式可以簡化操作,通過ipython manage.py shell查看render_to_response的執(zhí)行,實際也是返回
了一個HttpResponse對象
總結(jié)
以上是生活随笔為你收集整理的django 学习 (二) 模板的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Visual Studio 2005结合
- 下一篇: 定活两便利息怎么算?超详细!