Django模板(1)

  將頁面的設計和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>
View Code

代碼說明:ide

  • 用兩個大括號括起來的文字(例如 {{ person_name }} )稱爲 變量(variable) 。這意味着在此處插入指定變量的值。
  • 被大括號和百分號包圍的文本(例如 {% if ordered_warranty %} )是 模板標籤(template tag) 。標籤(tag)定義比較明確,即: 僅通知模板系統完成某些工做的標籤。
  • 這個例子中的模板包含一個for標籤( {% for item in item_list %} )和一個if 標籤({% if ordered_warranty %} )。for標籤相似Python的for語句,可以讓你循環訪問序列裏的每個項目。 if 標籤,正如你所料,是用來執行邏輯判斷的。 在這裏,tag標籤檢查ordered_warranty值是否爲True。若是是,模板系統將顯示{% if ordered_warranty %}和{% else %}之間的內容;不然將顯示{% else %}和{% endif %}之間的內容。{% else %}是可選的。
  • 這個模板的第二段中有一個關於filter過濾器的例子,它是一種最便捷的轉換變量輸出格式的方式。 如這個例子中的{{ship_date|date:」F j, Y」 }},咱們將變量ship_date傳遞給date過濾器,同時指定參數」F j,Y」。date過濾器根據參數進行格式輸出。 過濾器是用管道符(|)來調用的,具體能夠參見Unix管道符

2. 使用模板系統函數

  先不和視圖一塊兒使用,以獨立的方式使用,在Python代碼中使用Django模板的最基本方式以下:lua

  • 能夠用原始的模板代碼字符串建立一個 Template 對象, Django一樣支持用指定模板文件路徑的方式來建立 Template 對象;
  • 調用模板對象的render方法,而且傳入一套變量context。它將返回一個基於模板的展示字符串,模板中的變量和標籤會被context值替換。
>>> 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.
View Code

   建立了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
View Code

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.'
View Code

  一樣,也能夠經過句點來訪問對象的屬性。 比方說, 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.'
View Code

  句點也可用於訪問列表索引,例如:

>>> 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.'
View Code

  注意:不容許使用負數列表索引。 像 {{ 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 .'
View Code

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'
View Code

7. 模板標籤

  • if/else

  {% 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 %}
View Code
  • for

  {% for %} 容許咱們在一個序列上迭代。 與Python的 for 語句的情形相似,循環語法是 for in Y ,Y是要迭代的序列而X是在每個特定的循環中使用的變量名稱。 每一次循環中,模板系統會渲染在 {% for %} 和 {% endfor %} 之間的全部內容。

<ul>
{% for athlete in athlete_list %}
    <li>{{ athlete.name }}</li>
{% endfor %}
</ul>
View Code

  也能夠嵌套使用 {% for %} 標籤:

{% for athlete in athlete_list %}
    <h1>{{ athlete.name }}</h1>
    <ul>
    {% for sport in athlete.sports_played %}
        <li>{{ sport }}</li>
    {% endfor %}
    </ul>
{% endfor %}
View Code

  `` for`` 標籤支持一個可選的`` {% empty %}`` 分句,經過它咱們能夠定義當列表爲空時的輸出內容:

{% for athlete in athlete_list %}
    <h1>{{ athlete.name }}</h1>
    <ul>
    {% for sport in athlete.sports_played %}
        <li>{{ sport }}</li>
    {% endfor %}
    </ul>
{% endfor %}
View Code

  Django不支持退出循環操做。 若是咱們想退出循環,能夠改變正在迭代的變量,讓其僅僅包含須要迭代的項目。 同理,Django也不支持continue語句,咱們沒法讓當前迭代操做跳回到循環頭部。

相關文章
相關標籤/搜索