1. 程式人生 > >Django學習(3)模板定制

Django學習(3)模板定制

ase 我們 頻繁 ping upload shang star 2.0 asc

  在Django學習(一)一首情詩中,views.py中HTML被直接硬編碼在代碼之中,雖然這樣便於解釋視圖是如何工作的,但直接將HTML硬編碼到視圖卻不算一個好主意。因為:

  • 對頁面設計進行的任何改變都必須對Python代碼進行相應的修改,而站點設計的修改往往比底層Python代碼的修改要頻繁得多。
  • Python代碼編寫和HTML設計是兩項不同的工作,大多數專業的網站開發環境都將它們分配給不同的人員來完成。
  • 程序員編寫Python代碼和設計人員制作模板兩項工作同時進行的效率是最高的,遠勝於讓一個人等待另一個人完成對某個既包含Python又包含HTML的文件的編輯工作。

  基於以上原因,Django推薦使用模板。模板(Template)是一個文本,用於分離文檔的表現形式和內容。模板通常用於產生HTML.
  本次分享的目標是利用Django的模板來產生一封簡單的情書。這需要用到Django模板方面的知識。
  先新建項目love_letter:

django-admin.py startproject love_letter

切換到該文件夾下的love_letter目錄,新建letter.html文件,即Django的模板,代碼如下:

 1 <html>
 2 <head>
 3 <title>Love Letter</title>
 4 </head>
 5 <body>
 6 <h1>Love Letter for {{ name }}</h1>
 7 
 8 <p>Dear {{ name }}:</p>
 9
10 <p>Now you are reading a letter from your BF. Thanks for reading it.</p> 11 12 <p>We met on {{met_date}}, and today is {{today}}, so we have been together for {{days}} days.</p> 13 14 <p>Now you live in {{your_city}}, and I live in {{my_city}}. 15 {% ifequal your_city.lower my_city.lower %}
16 So lucky for living in the same city! 17 {% else %} 18 What a pity for not being together! 19 {% endifequal %} 20 </p> 21 22 <p>So glad to meet you! You must be the heaven-sent angel for you are 23 <ul> 24 {% for trait in traits %} 25 <li>{{trait}}</li> 26 {% endfor %} 27 </ul> 28 I‘m so fascinated of you! 29 </p> 30 31 <p> 32 It is now {{weather}} in {{your_city}}, 33 {% ifequal weather ‘cold‘%} 34 take care of yourself. 35 {% else %} 36 {% ifequal weather ‘hot‘%} 37 take care of yourself. 38 {% else %} 39 nice weather, isn‘t it? 40 {% endifequal %} 41 {% endifequal %} 42 43 Hoping for seeing you soon! May you have a pleasent day! 44 </p> 45 46 <p>Yours Sincerely,<br/>{{ today }}<br/>{{ author }}</p> 47 48 </body> 49 </html>

  我們有必要對這個模板做解釋:

  • {{ name }}表示name變量,所有{{...}}裏面包含的是變量。
  • {% ifequal your_city.lower my_city.lower %}為標簽(tag),表示if判斷語句,判斷兩個變量是否相等,需要用{% endifequal %}來結束。
  • {% for trait in traits %}為標簽,表示for循環語句,traits可以為list或者set序列,需要用{% endfor %}。
  • 其余代碼同HTML相同。

  定義好模板之後,我們應該告訴Django怎樣使用這個模板,因此,需要在settings.py中的TEMPLATES設置DIRS:

技術分享圖片


  這樣我們就能在視圖中使用該模板了。在相同的文件夾下,新建views.py,代碼如下:

 1 from django.shortcuts import render_to_response
 2 import datetime
 3 
 4 def output(request):
 5 c = {name:Rose,
 6 met_date: datetime.datetime(2016,5,24,18,0,0),
 7 today: datetime.datetime.now(),
 8 your_city: shanghai,
 9 my_city: Shanghai,
10 traits: [young and pretty, lovely and positive, warm-hearted and careful, independent and clever],
11 weather: cold,
12 author: Jclian
13 }
14 c[days] = (c[today] - c[met_date]).days
15 return render_to_response(letter.html, c)

其中c為字典,keys為模板中定義的變量,values可以自由定義。
  最後配置好urls.py,並開啟8000端口,在網頁中輸入localhost:8000,得到的頁面如下:


技術分享圖片



參考文獻:

  1. Django中文教程.pdf:http://download.csdn.net/download/huangzhichang13/8177581
  2. Django官方文檔之Templates:https://docs.djangoproject.com/en/2.0/topics/templates/

Django學習(3)模板定制