Simple template in Django
ลองมาดู template ใน Django กันบ้าง หลักการง่ายๆ ไม่ใช้ xml ไม่ใช่ Python ต้องง่ายกว่านั้น ทำงานได้สารพัด ไม่จำกัดรูปแบบ ขั้นแรกต้องบอกก่อนว่า template อยู่ที่ไหน ข้อมูลพวกนี้อยู่ใน settings.py เลือกใช้ได้ตามสภาพแวดล้อม
TEMPLATE_DIRS = ( '/home/sugree/work/git/django66/samplesite/templates' )
อย่าลืมสร้างไดเรกทอรีด้วย
mkdir templatesหน้าตา views.py จะเปลี่ยนไป
from django.template import Context, loader from django.http import HttpResponse def index(request): t = loader.get_template('helloworld/index.html') c = Context() return HttpResponse(t.render(c))
ตัดค่าคงที่ออกไป แล้วเอาไปใส่ใน templates/helloworld/index.html
Hello, World!
คำเตือน: ขอเปลี่ยนชื่อ view เป็น index เลยต้องแก้ urls.py ตามไปด้วย
urlpatterns = patterns('', (r'^$', 'samplesite.helloworld.views.index'), )
Roti (alpha) thinks you may like these:







อ่านตามเรื่อย ๆ เริ่มจะเห็นภาพ
context คงเป็นตัวเอาไว้ hold ค่าที่ retrieve จาก model ?
กลไกการ resolve view มัน hard code ไปนิด คงเป็นเหตุผลเรื่อง simplicity ผมสนใจว่ามี view แบบอื่นอีกมั้ยครับนอกจากแบบนี้
Post new comment