2014年11月5日 星期三

Django筆記(2)-完整的 html 網頁


步驟一
在 mysite/ 目錄下,建立名稱為 templates 的新目錄(這目錄負責放置 html 網頁)

步驟二
到 mysite/mysite/settings.py 中新增以下代碼

#將 templates 的路徑告知 Django
TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates'),
)

步驟三
撰寫名稱為 test.html 的網頁,並將該網頁放到 templates 目錄(完整代碼如下)

<html>
    <head>
        <title> test </title>
        <meta charset='utf-8'>
    </head>
    <body>
        <ul>
            <!-- 變量的定義在 views.py -->

            <!-- 打印 dict 類型 -->
            <li> 我的名字 : {{ me.name }} </li>
            <li> 我的興趣 : {{ me.interest }} </li>

            <!-- 打印 list 類型 -->
            <li> 水果A : {{ fruit.0 }} </li>
            <li> 水果B : {{ fruit.1 }} </li>

            <!-- 打印普通的變數 -->
            <li> 一般變數 : {{ varTest }} </li>
        </ul>
    </body>
</html>

步驟四
修改 mysite/mysite/views.py (完整代碼如下)

from django.shortcuts import render_to_response
from django import template

def helloWorld(request):
    me = {'name':'Jacky', 'interest':'coding' }
    fruit = ['apple', 'banana']
    varTest = 123456
    return render_to_response('test.html',locals())


步驟五
開啟server後~
在網址列輸入 127.0.0.1:8000/helloWorld/ 觀看結果

                                                                    上一篇    回目錄    下一篇

沒有留言:

張貼留言