angrykola

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

加载模板:

使用django提哦那个的API,首先将模板的保存位置告诉框架, 设置settings.py。

#settings.py
TEMPLATE_DIRS = ( ... "D:/web/mysite/templates", #注意在python中是使用反斜杠“/” )

第二部:修改视图文件

 1 #views.py
 2 from django.template.loader import get_template
 3 from django.template import Context
 4 from django.http import HttpResponse
 5 import datetime
 6 
 7 def current_datetime(request):
 8     now = datetime.datetime.now()
 9     t = get_template('current_datetime.html')   
10     html = t.render(Context({'current_date': now}))  
11     return HttpResponse(html)

记得编写你的模块文件:

#D:\web\mysite\templates current_datetime.html
<html><body>It is now {{ current_date }}.</body></html>

现在开启服务器,打开页面 http://127.0.0.1:8000/time/ 会看到完整解析后的页面。 

下面使用 render_to_response() 重新编写 current_datetime 范例:

from django.shortcuts import render_to_response 
...

def current_datetime(request):
    now = datetime.datetime.now()
    #t = get_template('current_datetime.html')
    #html = t.render(Context({'current_date':now}))
    #return HttpResponse(html)
    return render_to_response('current_datetime.html',locals())      #locals简化代码

重写后代码简化了不少。

 

posted on 2013-11-14 23:05  kolaman  阅读(179)  评论(0)    收藏  举报