7 ตุลาคม 2557

Published ตุลาคม 07, 2557 by with 0 comment

Django บน Python ตอนที่ 7: Template

Template เป็นแม่แบบสำหรับหน้าเว็บเพจ โดยสามารถเขียนในรูปแบบ HTML ได้ ช่วยให้เราสามารถปรับแต่งได้อย่างอิสระ โดย Template จะถูกเรียกนำมาใช้งานร่วมกับ Views โดยจะทำการประมวลผลร่วมกับคำสั่งต่าง ๆ และ models ของ  Django ในภาษา Python แล้วจะส่งหน้าเว็บเพจออกมาในรูปแบบ HTML
บทความนี้ผมจะพาผู้อ่านไปทำ Template ของ Django กันครับ
อ่านบทความย้อนหลังได้ที่ python3.wannaphong.com/search/label/Django 
ให้ผู้อ่านสร้าง project ชื่อ a4 แล้วเข้าไปยังโฟลเดอร์ a4
python django-admin.py startproject a4

ให้สร้าง app โดยใช้คำสั่ง
python manage.py  startapp hello

แล้วให้ผู้อ่านสร้าง โฟลเดอร์ template ในโฟลเดอร์หลัก a4 ให้สร้างไฟล์ base.html แล้วใส่โค้ดตามนี้
<html>
    <head>
    <title>I am Template</title>
    </head>
    <body>
        <h1>Welcom to My web</h1>
        <h1>{% block content %}
        {% endblock %}</h1>
    </body>
</html>

บันทึกไฟล์ ต่อมาสร้างไฟล์ home.html
{% extends "base.html" %}
{% block content %}
{{ hello }}
{% endblock %}
บันทึกไฟล์ เสร็จแล้วให้เข้าไปยังโฟลเดอร์ hello แล้วเปิดไฟล์ views.py เพิ่มโค้ดลงไปดังนี้
from django.http import HttpResponse
from django.template.loader import get_template
from django.template import Context

def index(request):
    hello = "Hello World!"
    t = get_template("home.html")
    html = t.render(Context({'hello':hello}))
    return HttpResponse(html)

เสร็จแล้วบันทึกไฟล์ ให้เข้าไปแก้ไขไฟล์ settings.py ตรง
INSTALLED_APPS = (
    ..
    ..
    'hello', 
)

ให้ใส่ 'hello', ลงไปครับ ต่อมาแก้ไขตรง
TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

ให้เพิ่มที่อยู่ของโฟลเดอร์ template ในระบบไฟล์ของเครื่อง ที่เราสร้างลงครับ ตัวอย่างเช่นของผมเป็น
TEMPLATE_DIRS = (
    'C:/django/a4/template',
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

บันทึกไฟล์เสร็จ ให้ผู้อ่านเปิดไฟล์ urls.py แก้ไขตรง
urlpatterns = patterns('',
    url(r'^$', 'hello.views.index'), #กำหนดให้หน้าหลักเรียกใช้งาน app hello ไฟล์  views.py ตรงที่  index
)

เรียบร้อยแล้วลองรันดูครับ
python manage.py runserver

เข้ามาที่ http://127.0.0.1:8000/ จะพบกับ

โค้ดตัวอย่าง http://bit.ly/1reXK1P
ติดตามบทความต่อไปนะครับ
ขอบคุณครับ

0 ความคิดเห็น:

แสดงความคิดเห็น

แสดงความคิดเห็นได้ครับ :)