1. 程式人生 > 其它 >第三章、模板

第三章、模板

1、模板的基本使用:

  

2、模板變數進行變數的查詢:模板系統能夠非常簡潔地處理更加複雜的資料結構,例如list、 dictionary和自定義的物件。

  

3、模板標籤和過濾器:

  

    除以上幾點以外的所有東西都視為 True。{% if %} 標籤接受 and , or 或者 not 關鍵字來對多個變數做判斷 ,或者對變數 取反( not )

    

    

      

4、使用模板來來代替html的標籤

5、配置模板的路徑和使用

  1)配置模板路徑:開啟setting.py,找到TEMPLATE_DIRS引數,修改為:

    TEMPLATE_DIRS = (

      os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),

    )

  2)在mysite資料夾下新建模板資料夾:,再建一個time.html檔案,寫入程式碼:

<html><body>It is now {{ current_date }}.</body></html>

  3)修改new_time試圖為:

from django.template.loader import get_template
def new_now_time(request):
    now 
= datetime.datetime.now() t = get_template('time.html') html = t.render({'current_date': now}) return HttpResponse(html)

還可以使用另一種方式:

def new_now_time(request):
    now = datetime.datetime.now()
    return render_to_response('time.html', {'current_date': now})

還可以使用locals

def current_datetime(request):
    current_date 
= datetime.datetime.now() return render_to_response('time.html', locals())