iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 28
0
自我挑戰組

Cloud/SDN/SFC...菜鳥的學習筆記系列 第 28

DAY 28 Django 簡易入門教學(五)-建立模版

Django 模版(Template)

在使用模版之前,我們要先在 settings.py 搜尋 TEMPLATES ,我們會看到以下設定:

請在 DIRS 中加入os.path.join(BASE_DIR, 'templates'),如下所示:

'DIRS': [os.path.join(BASE_DIR, 'templates')]是指到 BASE_DIR/templates 文件夾中去取模板,指定公用的 templates 路徑讓所有 apps 都可以調用,非常方便。

接著,建立一個 templates 的資料夾,並在裡面建立一個 hello_world.html
現在,我們的檔案結構如下:

hello_world.html :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>hello_world</title>
</head>
<body>
    <h1>hello_world!</h1>
</body>
</html>

然後進入 myapp/views.py 中,修改 hello_world:

from django.shortcuts import render
from django.http import HttpResponse

def hello_world(request):  
   return render(request, 'hello_world.html') #修改

def add(request, a, b):
    s = int(a) + int(b)
    return HttpResponse(s)

之後我們前往 http://127.0.0.1:8000/hello/ ,就能看見 template 回傳的 hello_world 頁面喔!

接下來,讓我們來玩一點變化。
修改 myapp/views.py 中的 hello_world:

def hello_world(request): #修改
    a = 10
    b = 5
    s = a + b
    d = a - b
    p = a * b
    q = a / b
    return render(request, 'hello_world.html',locals())

locals()函數會以字典類型返回當前位置的全部局部變量。
因此使用locals()就不用一個一個手動輸入欲回傳的變量囉~

修改 hello_world.html :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>hello_world</title>
</head>
<body>
    <h1>hello_world!</h1>
    <p>a = {{a}}</p>
    <p>b = {{b}}</p>
    <p>a + b = {{s}}</p>
    <p>a - b = {{d}}</p>
    <p>a * b = {{p}}</p>
    <p>a / d = {{q}}</p>
</body>
</html>

{{<variable_name>}} 是在 Django Template 中顯示變數的語法。

接著,當我們再次前往 http://127.0.0.1:8000/hello/

我們可以發現,我們在 views.py 中修改的 hello_world 裡面的參數成功傳到頁面上了!

今天的介紹就到這裡,明天就來建立 Django 模型(Model) 吧!


上一篇
DAY 27 Django 簡易入門教學(四)-建立 Django 視圖
下一篇
DAY 29 Django 簡易入門教學(六)-建立資料庫與模型(Model)
系列文
Cloud/SDN/SFC...菜鳥的學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言