วันศุกร์ที่ 11 มกราคม พ.ศ. 2562

[Django] template

Template

-การออกแบบหน้าต่างเว็บไซต์ด้วย HTML หรือ Javascript แล้วนำมาใช้งาน
-เป็นการทำงานในส่วนการ design ไม่เกี่ยวข้องกับ logic
-เรียกใช้งานผ่านไฟล์ views.py
-แก้ไข ส่วน DIRS ของ TEMPLATES ใน setting.py


การใช้งาน template
1.สร้างไฟล์ html ชื่อว่า hello.html


<!DOCTYPE html>
<html>

  <head>
     <meta charset="utf-8">
     <title>Django</title>
  </head>

  <body>
     <h1>Hello world</h1>
     <h2>Welcome to my world</h2>
  </body>

</html>


2.ระบุตำแหน่งที่อยู่ของไฟล์ในส่วน TEMPLATES ที่อยู่ในไฟล์ settings.py เพื่อเป็นการบอกกับ Django ว่าเราเสร้าง template ไว้ที่ใด

hello.html อยู่ในโฟลเดอร์ template ภายใน app hello

3. การนำมาใช้งาน

กรณีที่เราไม่ได้ใช้งาน template ที่สร้างไว้จะมีการสั่งให้แสดงโดยตรง

from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):

return HttpResponse("<h1>Hello World</h1>")

แต่ในกรณีที่มีการใช้งาน template จะต้องทำการโหลดไฟล์เข้ามาก่อน ซึ่งการโหลดไฟล์ทำได้หลายวิธี เช่น
get_template(template_name)
  โหลดมาใช้งาน 1 template
select_template(template_name_list)
  โหลดมาใช้งานหลายๆ template
Template.render(context=None, request=None)
  มีการเก็บข้อมูลเป็นแบบ dictionary และในการใช้งานจะต้องเรียก context และ request
(context หมายถึง dictionary ที่มี key เป็น ชื่อตัวแปร และ value เป็น ค่าของตัวแปรนั้นๆ ที่จะนำมาใช้งาน )

from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
# Create your views here.
def index(request):
template = loader.get_template("hello.html")



return HttpResponse(template.render())

การแสดงผลจากการใช้งาน template

ทดลองใช้งาน Tag ในไฟล์ html
          ทดลองแก้ไขส่วน body ในไฟล์ html

<body>
<h1>Hello everybody</h1>
<h2>welcome to my world</h2>
<hr>
<h2>name : {{name}}</h2>
<h2>Age : {{age}}</h2>
{% if age <= 15%}
<h3>Group : younger</h3>
{% elif age <= 30%}
<h3>Group : adult</h3>
{%else%}
<h3>Group : Older</h3>
{%endif%}
</body>

          ใช้ {{name}} ให้รับค่าจากตัวแปร name มาแทนค่าลงในตำแหน่ง
           ใช้ {% if age <= 15%} เพื่อเป็นการทดสอบเงื่อนไข เมื่อเข้าเงื่อนไขใดให้ทำตามคำสั่งนั้นๆ

ไฟล์ one.html
<! DOCTYPE html>
<html>

    <head>
<meta charset="UTF-8">
<title>Django</title>
<style media="screen">
      body{
            background-color:rgb(192, 237, 255)
            }
         </style>
    </head>

    <body>
<h1>Hello everybody</h1>
<h2>welcome to my world</h2>
<hr>
<h2>name : {{name}}</h2>
<h2>Age : {{age}}</h2>
{% if age <= 15%}
<h3>Group : younger</h3>
{% elif age <= 30%}
<h3>Group : adult</h3>
{%else%}
<h3>Group : Older</h3>
{%endif%}
     </body>




</html>

--------------------------------------------------------------------
def profile(request):
template1 = loader.get_template("one.html")
info = {
'name':"iceiceice",
'age':19,
}
return HttpResponse(template1.render(info,request))



ไม่มีความคิดเห็น:

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