close

 2017.08.22 

資料來源: (1)https://djangobook.com/the-django-book/

Django Templates

      在上篇文章中我們己經成功了呈現了字串"Hello World",簡單地說我們己經可以Web Server作互動了
下面我們要更進一步了解Django Templates的使用方式。故事仍舊要從到我們的MTV架構開始談起。
(資料來源:http://blog.easylearning.guru/implementing-mtv-model-in-python-django/)

在上篇文章中我們的Hello World 網頁使用到了最短路徑,所以使用到了URLS, Views二個元件,其實你也可以使用Python+HTML這種方式土法煉鋼打造你的網站,但是它存在一些問題。
例如可以在view中同時使用Python+HTML去反應使用者的要求。


def current_datetime(request): now = datetime.datetime.now() html = "<html><body>It is now %s.</body></html>" % now return HttpResponse(html)

任何網頁或資料庫設定改變需要改變相對應的python程式碼,我們希望設計改變可以不需要改變Python程式碼。Python and HTML 是二種不同的設計原則,所以為了有效的設計及使用我們使用Tempaltes分開html及python的方式去設計網頁。

 Django Templates 基本概念

Templates依據定義是一個文字字串文件,它的用途是為了分開文件中的資料呈現,在Templates會定義Templates tags去規範文件如何呈現,通常Templates是用來儲存HTML的程式碼。從下面的例子學習如何使用templates 。

 

<html>
<head>
    <title>Ordering notice</title>
</head>
<body>
    <h1>Ordering notice</h1>
    <p>Dear {{ person_name }},</p>
    <p>Thanks for placing an order from {{ company }}. It's scheduled to ship on {{ s\
hip_date|date:"F j, Y" }}.</p>
    <p>Here are the items you've ordered:</p>
    <ul>
        {% for item in item_list %}
        <li>{{ item }}</li>{% endfor %}
    </ul>
    {% if ordered_warranty %}
    <p>Your warranty information will be included in the packaging.</p>
    {% else %}
    <p>
        You didn't order a warranty, so you're on your own when the products inevitably stop working.
    </p>
    {% endif %}
    <p>Sincerely,<br />{{ company }}</p>
</body>
</html>
  •  Templates 大部份儲存HTML程式碼,再加上
  • {{ person_name }} 是一個變數值
  • {% if ordered_warranty %}是 template tag,它比較類似python的程式碼。例如 python的if , for 程式碼
  •  {{ ship_date|date:"F j, Y" }} 是 template filter,它可用來很方更地改變變數的呈現格式。
  • context 是一個 name->value 對應 (類似Python的dictionary),它傳值給 template。
  • template renders 是一個從context取代變數值到指定的模板。
  • 更多template tag 和 template filter 參考https://djangobook.com/basic-template-tags-filters/
  • Advanced 參考https://djangobook.com/advanced-templates/
  • 建議先連結上面二個連結預習一下所有的tag & Filter

 

Templates in Views

如何將Templates整合至Views中,有下面幾種整合方式
(1)Templates 字串匯入

from django.template import Template, Context
from django.http import HttpResponse
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    t = Template("<html><body>It is now {{ current_date }}.</body></html>")
    html = t.render(Context({'current_date': now}))
    return HttpResponse(html)
  • 第一行匯入Templates 的Context,其內部包含許多定義好的變數及變數值。
  • html 程式碼不長,利用Templates 字串方式

(2)Templates 文件匯入

 

from django.template import Template, Context
from django.http import HttpResponse
import datetime

def current_datetime(request):

    now = datetime.datetime.now()
    # Simple way of using templates from the filesystem.
    # This is BAD because it doesn't account for missing files!
    fp = open('\users\djangouser\templates\mytemplate.html')
    t = Template(fp.read())
    fp.close()

    html = t.render(Context({'current_date': now}))
    return HttpResponse(html)

 

  • 利用open 檔案的方式匯入。
  • 缺點是檔案或路徑不對時會產生錯誤。

(3)指定Templates 文件存放目錄匯入

打開 settings.py 然後在\mysite 建一個 \templates 目錄並加入


TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates'),
)

 #-------------------------------------------

好了, 現在回到我們的主題view,總共要修改三步驟

(1)用編輯器修改在\mysite_project\settings.py 新增



TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates'),
)

(2)用編輯器修改在\mysite_project\mysite_app下的view.py

#mysite\mysite\views.py

from django.shortcuts import render
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    return render(request, 'current_datetime.html', {'current_date': now})

第一個參數為: request 物件
第二個參數:使用的template 檔名 
第三個參數:Context 物件,如空白,則為空Context

(3)在\mysite_project\mysite_app下建一個\templates 子目錄,並且在這個目錄下編寫一個current_datetime.html 檔案

內容如下


<html>
    <body>
        It is now {{ current_date }}
    </body>
</html>

特別注意: 如你的網頁要顯示中文,這個檔案格式要存成UTF8格式。

 

Views 和 Templates 整合測試

在瀏覽器輸入 http://127.0.0.1:8000/time/,你會看到網頁顯示現在時間

  成功了嗎,如不成功再回頭看看那裡有問題,應該不會很困難。

另外利用這個機會改一下語言及時區,修改settings.py 檔案內設定為

LANGUAGE_CODE = 'zh-TW'
TIME_ZONE = 'Asia/Taipei'

回Django Web 程式設計主目錄



 

 

 

 

 

    

 

 

 

 

 

 

 

arrow
arrow
    文章標籤
    Django Templates
    全站熱搜

    stanley 發表在 痞客邦 留言(0) 人氣()