You are hereLoop in template

Loop in template


By sugree - Posted on 24 September 2008

อยากทำ Hangman แต่ยังไม่มีเวลาว่างยาวพอที่จะเริ่ม ช่วงนี้เลยเปลี่ยนวิธีทำงาน ลด time quantum ลงด้วย rtm แทนทึ่จะเขียนทีละ 1 ชั่วโมงก็ลดให้เหลือแค่ 15 นาที หัวข้อก็จะสั้นหน่อย

วันนี้เริ่ม Hangman ซะที

python manage.py startapp hangman

<!--break-->

แล้วมาว่ากันทีละเรื่อง เริ่มจาก hangman/views.py เหมือนเดิม ไม่มีอะไรมาก แต่ส่ง list เข้ามาใน context

from django.template import RequestContext
from django.shortcuts import render_to_response
 
def index(request):
    choices = [chr(65+i) for i in range(26)]
    return render_to_response('hangman/index.html',
                              {'choices': choices},
                              context_instance=RequestContext(request))

แล้วก็เซ็ต hangman/urls.py ให้รู้จัก view

from django.conf.urls.defaults import *
 
urlpatterns = patterns('',
    (r'^$', 'django66.hangman.views.index'),
)

ถัดมาก็เชื่อมกับโปรเจคใน urls.py

urlpatterns = patterns('',
    (r'^hangman/', include('django66.hangman.urls')),
)

ปิดท้ายด้วย templates/hangman/index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>   
 <title>Django HangMan</title>
</head>
<body>
{% for c in choices %}
{{ c }}
{% endfor %}
</body>
</html>

ที่อยากให้ดูก็คืออันสุดท้าย หน้าตาที่แท้จริงของ template ใส่ loop แล้วเป็นแบบนี้นี่แหละ