上一節中的輸入,即視圖中的return HttpResponse()部分。函數中的内容為<html><body>……
意思就是,前端檔案,要每次都要手寫,列印,這非常麻煩。通常,它會包括很多内容,還有js檔案,css檔案等。而且設計頁面也不好設計,或者設計好了,再粘貼html字串,進行輸出。且會發現html代碼與python背景代碼摻雜在一起。
1 通過自定義,
直接在視圖中寫。建立立視圖(函數)hello_who如下:
def hello_who(request):
t=template.Template('hello {{name}}')
c=template.Context({'name':'宋江'})
return HttpResponse(t.render(c))
通過建立模闆,輸出hello,who
這裡who的名字為中文的宋江。,如果在頁面中正常顯示中文,需要在settings.py中設定LANGUAGE_CODE = 'zh-cn'
且在視圖檔案views.py中,第一行加入#encoding=utf-8
2 使用模闆
先建立模闆檔案,檔案名任意。模闆檔案就是html前台檔案。與aspx頁類似。先建立一個hello.html檔案。如下:
<html>
<body>
<div style="color:red;"><b>Hello,{{name}}</b></div>
</body>
</html>
然後在視圖中加載這個模闆,并給變量指派。
視圖hello_who改為:
t = get_template('hello.html')
html = t.render(Context({'name': '宋江'}))
return HttpResponse(html)
其中,獲得模闆,和呈現函數,可以利用一個函數實作,如下:
return render_to_response('hello.html', {'name': '宋江'})
另使用這個函數,需要引入:
from django.shortcuts import render_to_response
通過locals()傳回所有定義的映射
name= '宋江'
return render_to_response('hello.html', locals())
部落格園大道至簡
http://www.cnblogs.com/jams742003/轉載請注明:部落格園