載入html

      在〈載入html〉中留言功能已關閉

上一章節中,在index.py裏撰寫了一連串的html字串,每行都要用 ‘\’來隔開,然後再用HttpResponse產生html文件傳送到客戶端的瀏覽器中。
光看到每行後面都有  ‘\’ 就會開始懷疑人生,所以把 html獨立出來成立一個新的檔案,才是網頁設計的王道。

html 存放位置

請在虛擬網站下建立 templates 目錄。目錄如下

d:\web
├─  venv #虛擬環境設定
├─  thomas #thomas網站
│   ├─  thomas #設定檔目錄
│   ├─  templates #模組目錄
│   │   ├─ home.html
│   │   ├─ travel.html
│   ├─  home #home app目錄
│   │   ├─  home.py #首頁
│   ├─  travel #travel app目錄
│   │   ├─  travel.py #首頁

DIRS設定

修改 settings.py 如下藍色的地方

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates').replace('\\', '/')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

新增首頁App

上一篇的首頁只有一個很單純的 index.py 檔案,在Django中把 index.py 視為一支 app。但專案通常是有好幾支app所組成的,而每一個app又可能由好幾支 .py 程式組成。

所以我們也可以建立 app 目錄,再於此目錄新增其他的 .py檔,底下說明建立首頁 home的 app。

1. 建立 home app
2. 撰寫 views.py
3. 安裝home app
4. 設定網址連結

d:\web
├─ venv #虛擬環境設定
├─ thomas #thomas網站
│ ├─ home #home app目錄
│ │ ├─ home.py #首頁
│ ├─ templates #模組目錄
│ │ ├─ home.html #首頁 │ ├─ thomas #設定檔目錄

建立home app

python manage.py startapp home

撰寫網頁

在home目錄下已經自動新增一個 views.py檔,此檔就是這個App主要的 Python 程式。views.py 幾乎都是固定的,只有第三個參數傳入的變數字典要改變而以。

from django.shortcuts import render
from datetime import datetime
def html(request):
    return render(request, 'home.html',{'current_time': str(datetime.now()),})

前一篇的HttpResponse方法是直接由 .py檔產生HttpResponse物件。

而上述的render是用來取代HttpResponse方法的。render會載入第二個參數所指定的 html 模組,並依第三個參數將變數傳入html模組內,然後產生HttpResponse物件。render的參數說明如下

第一個參數 : request: HttpRequest物件
第二個參數 : Template名稱(html名),對應於 BASE_DIR/templates 目錄
第三個參數 : 新增到 html 模組裏的變數字典,需為Dictionary格式

然後在templates下新增 home.html

<!DOCTYPE html>
<html>
    <head>
        <title>I come from template!!</title>
        <style>
            body {
               background-color: lightyellow;
            }
            em {
                color: LightSeaGreen;
            }
        </style>
    </head>
    <body>
        <h1>Hello World!</h1>
        <em>{{ current_time }}</em>
    </body>
</html>

請注意, <em>{{ current_time }}</em> 可以由Python中使用字典將其值傳入

安裝app

在settings.py裏新增 ‘home’. 另外也可以使用 ‘home.apps.HomeConfig’

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'home',
    #也可以使用 'home.apps.HomeConfig',
    'travel',
]

連結

更新urls.py如下

from django.contrib import admin
from django.urls import path, include
import home.home as home
import travel.views as travel
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', travel.html),
]

模版簡介

底下以九九乘法表說明程式的寫法

99.py的語法如下

from django.shortcuts import render
from django.http import HttpResponse
from datetime import datetime
def html(request):
    i=range(1,10)
    j=range(1,10)
    return render(request, '99.html', {'currentTime': str(datetime.now()),'var_i':i, 'var_j':j})

home.html語法如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>Hello World!</h1>
    <em>{{ currentTime }}</em>
    <table border="1" cellpadding="0" cellspacing="0">
    {% for i in var_i %}
        <tr>
            {% for j in var_j %}
                <td width="50">{% widthratio i 1 j %}</td>
            {% endfor %}
        </tr>
    {% endfor %}
    </table>
</body>
</html>

{% for %} …. {% endfor %} 稱為 template tags,這是設計在html中可以簡易使用迴圈的語法

Template tags

如上的迴圈 {% for %} .. {% endfor %}就是其中之一的 template tags,另外也有 {% if %}..{% else %}{% endif %}

todo

Template Filter

https://djangogirlstaipei.gitbooks.io/django-girls-taipei-tutorial/content/django/template_tags.html

todo