Template可以幫助我們將前端程式碼獨立,這有什麼好處呢 ?
我們回到外面nuts的資料夾目錄
建立一個templates的資料夾,之後把前端的檔案放入
mkdir templates
接著引入之後,我們要在settings.py告訴它我們templates導引方向(DIR)
更改紅框起來的這段,在[]裡面加上os.path python的原生語法
[os.path.join(BASE_DIR, 'templates').replace('\\', '/')]
接著我們到templates建立自己喜歡的html我這邊取名為template_whoami
我們暫時先把CSS也寫在裡面,後面會在教各位如何把CSS獨立出來
<!DOCTYPE html>
<html>
    <head>
        <title>who am i</title>
        <style>
            body {
               background-color: black;
            }
            h1,h3 {
              color : white;
            }
        </style>
    </head>
    <body>
        <h1>I am David!</h1>
        <h3>{{ now }}</h3>
    </body>
</html>
寫好HTML後,接著view裡面更改我們剛剛的hello_world functions,在這邊假設帶入的是現在的時間,我們用python datetime的package,用datetime.now()輸出再轉string給now
from datetime import datetime
def hello_world(request):
    return render(request, 'template_whoami.html', {
        'now': str(datetime.today()),
    })
這時候,神奇的事發生了!

對的,我們剛剛的{{}}幫我們把變數代換了
那我們可以再拿幾個Python語法來替換玩玩看
def hello_world(request):
    return render(request, 'template_whoami.html', {
        'now': sum(range(1,101)),
    })
sum(range(1,101)) => 1+..+100 = 5050
有python整個人生都變簡單啦
那這時來看看網頁

5050就出現啦,如果懷疑計算錯誤的話趕緊拿計算機算哈哈
想再試試其他的趕緊!