將頁面的設計和Python的代碼分離開會更乾淨簡潔更容易維護。 咱們可使用 Django的 模板系統 (Template System)來實現這種模式,這就是本章要具體討論的問題。html
模板是一個文本,用於分離文檔的表現形式和內容。 模板定義了佔位符以及各類用於規範文檔該如何顯示的各部分基本邏輯(模板標籤)。 模板一般用於產生HTML,可是Django的模板也能產生任何基於文本格式的文檔。django
1. 一個簡單例子數據結構
該模板描述了一個向某個與公司簽單人員致謝 HTML 頁面。 可將其視爲一個格式信函:app
<html> <head><title>Ordering notice</title></head> <body> <h1>Ordering notice</h1> <p>Dear {{ person_name }},</p> <p>Thanks for placing an order from {{ company }}. It's scheduled to ship on {{ ship_date|date:"F j, Y" }}.</p> <p>Here are the items you've ordered:</p> <ul> {% for item in item_list %} <li>{{ item }}</li> {% endfor %} </ul> {% if ordered_warranty %} <p>Your warranty information will be included in the packaging.</p> {% else %} <p>You didn't order a warranty, so you're on your own when the products inevitably stop working.</p> {% endif %} <p>Sincerely,<br />{{ company }}</p> </body> </html>
代碼說明:ide
2. 使用模板系統函數
先不和視圖一塊兒使用,以獨立的方式使用,在Python代碼中使用Django模板的最基本方式以下:lua
>>> from django import template >>> t = template.Template('My name is {{ name }}.') >>> c = template.Context({'name': 'Adrian'}) >>> print t.render(c) My name is Adrian. >>> c = template.Context({'name': 'Fred'}) >>> print t.render(c) My name is Fred.
建立了Template對象,可使用context來傳遞數據給它。一個context是一系列變量和它們值的集合。context在Django裏表現爲 Context 類,在 django.template 模塊裏。 她的構造函數帶有一個可選的參數: 一個字典映射變量和它們的值。 調用 Template 對象 的 render() 方法並傳遞context來填充模板:spa
3. 同一個模板,多個上下文設計
一旦有了 模板 對象,你就能夠經過它渲染多個context, 例如:code
>>> from django.template import Template, Context >>> t = Template('Hello, {{ name }}') >>> print t.render(Context({'name': 'John'})) Hello, John >>> print t.render(Context({'name': 'Julie'})) Hello, Julie >>> print t.render(Context({'name': 'Pat'})) Hello, Pat
4. 深度變量的查找
模板系統可以很是簡潔地處理更加複雜的數據結構,例如list、dictionary和自定義的對象。在 Django 模板中遍歷複雜數據結構的關鍵是句點字符 (.)。好比,假設你要向模板傳遞一個 Python 字典。 要經過字典鍵訪問該字典的值,可以使用一個句點:
>>> from django.template import Template, Context >>> person = {'name': 'Sally', 'age': '43'} >>> t = Template('{{ person.name }} is {{ person.age }} years old.') >>> c = Context({'person': person}) >>> t.render(c) u'Sally is 43 years old.'
一樣,也能夠經過句點來訪問對象的屬性。 比方說, Python 的 datetime.date 對象有 year 、 month 和 day 幾個屬性,你一樣能夠在模板中使用句點來訪問這些屬性:
>>> from django.template import Template, Context >>> import datetime >>> d = datetime.date(1993, 5, 2) >>> d.year 1993 >>> d.month 5 >>> d.day 2 >>> t = Template('The month is {{ date.month }} and the year is {{ date.year }}.') >>> c = Context({'date': d}) >>> t.render(c) u'The month is 5 and the year is 1993.'
句點也可用於訪問列表索引,例如:
>>> from django.template import Template, Context >>> t = Template('Item 2 is {{ items.2 }}.') >>> c = Context({'items': ['apples', 'bananas', 'carrots']}) >>> t.render(c) u'Item 2 is carrots.'
注意:不容許使用負數列表索引。 像 {{ items.-1 }} 這樣的模板變量將會引起`` TemplateSyntaxError``。
5. 如何處理無效變量
默認狀況下,若是一個變量不存在,模板系統會把它展現爲空字符串,不作任何事情來表示失敗。 例如:
>>> from django.template import Template, Context >>> t = Template('Your name is {{ name }}.') >>> t.render(Context()) u'Your name is .' >>> t.render(Context({'var': 'hello'})) u'Your name is .' >>> t.render(Context({'NAME': 'hello'})) u'Your name is .' >>> t.render(Context({'Name': 'hello'})) u'Your name is .'
6.上下文(context)對象
多數時間,你能夠經過傳遞一個徹底填充(full populated)的字典給 Context() 來初始化 上下文(Context) 。 可是初始化之後,你也可使用標準的Python字典語法(syntax)向``上下文(Context)`` 對象添加或者刪除條目。
>>> from django.template import Context >>> c = Context({"foo": "bar"}) >>> c['foo'] 'bar' >>> del c['foo'] >>> c['foo'] Traceback (most recent call last): ... KeyError: 'foo' >>> c['newvariable'] = 'hello' >>> c['newvariable'] 'hello'
7. 模板標籤
{% if %} 標籤檢查(evaluate)一個變量,若是這個變量爲真(即,變量存在,非空,不是布爾值假),系統會顯示在 {% if %} 和 {% endif %} 之間的任何內容,例如:
{% if today_is_weekend %} <p>Welcome to the weekend!</p> {% endif %} {% if today_is_weekend %} <p>Welcome to the weekend!</p> {% else %} <p>Get back to work.</p> {% endif %}
{% for %} 容許咱們在一個序列上迭代。 與Python的 for 語句的情形相似,循環語法是 for X in Y ,Y是要迭代的序列而X是在每個特定的循環中使用的變量名稱。 每一次循環中,模板系統會渲染在 {% for %} 和 {% endfor %} 之間的全部內容。
<ul> {% for athlete in athlete_list %} <li>{{ athlete.name }}</li> {% endfor %} </ul>
也能夠嵌套使用 {% for %} 標籤:
{% for athlete in athlete_list %} <h1>{{ athlete.name }}</h1> <ul> {% for sport in athlete.sports_played %} <li>{{ sport }}</li> {% endfor %} </ul> {% endfor %}
`` for`` 標籤支持一個可選的`` {% empty %}`` 分句,經過它咱們能夠定義當列表爲空時的輸出內容:
{% for athlete in athlete_list %} <h1>{{ athlete.name }}</h1> <ul> {% for sport in athlete.sports_played %} <li>{{ sport }}</li> {% endfor %} </ul> {% endfor %}
Django不支持退出循環操做。 若是咱們想退出循環,能夠改變正在迭代的變量,讓其僅僅包含須要迭代的項目。 同理,Django也不支持continue語句,咱們沒法讓當前迭代操做跳回到循環頭部。