Django Templates

   อัปเดตล่าสุด April 20, 2023

Templates คือโฟลเดอร์ที่ใช้เก็บ HTML  ไฟล์ เพื่อที่จะให้ views สามารถ render หน้า HTML ออกไปแสดงผลได้


สร้างไฟล์ HTML ขึ้นมาใหม่ 2 ไฟล์ นั่นก็คือ  home.html   และ  post-detail.html   ซึ่งจะถูกเก็บอยู่ในโฟลเดอร์   templates/  ละ  blog เป็นโฟลเดอร์สุดท้าย ตามลำดับ ซึ่งนี่คือ Best Practice ในการวาง HTML Path สำหรับ Django

Django Templates Path

blog/
    templates/
        blog/
            home.html
            post-detail.html
    admin.py
    models.py
    views.py
    ...


 home.html

<!--home.html-->
<!DOCTYPE html>
<html>
<head>
    <title>Home | DH</title> 
</head>
<body>
    <h1>Hello, Django Tutorial</h1>

    {% for post in posts %}
      <ul>
        <li><a href="{% url 'post_detail' post.id %}">{{ post.title }}</a></li>
      </ul>
    {% endfor %}

</body>
</html>



 post-detail.html

<!--post-details.html-->
<!DOCTYPE html>
<html>
<head>
    <title>{{ post.title }} | DH</title> 
</head>
<body>

    <h1>Title: {{ post.title }}</h1>
    <p>Body: {{ post.body }}</p>

</body>
</html>


รันเซิร์ฟเวอร์

$ python manage.py runserver

เข้าดูที่ URL http://127.0.0.1:8000/ จะได้หน้า Homepage ตามภาพด้านล่าง ซึ่งตอนนี้ยังไม่มีโพสต์ใด ๆ แสดง เพราะว่ายังไม่ได้สร้างโพสต์นั่นเอง




คอร์สเรียนแนะนำ