這會導致幾個問題:
1,顯然,任何頁面的改動會牽扯到Python代碼的改動
網站的設計改動會比Python代碼改動更頻繁,所以如果我們將兩者分離開會更方便
2,其次,寫后臺Python代碼與設計HTML是不同的工作,更專業的Web開發應該將兩者分開
頁面設計者和HTML/CSS程序員不應該編輯Python代碼,他們應該與HTML打交道
3,程序員寫Python代碼同時頁面設計者寫HTML模板會更高效,而不是一個人等待另一個人編輯同樣的文件
因此,使用Django的模板系統分離設計和Python代碼會更干凈更易維護
模板系統基礎
Django模板是一個string文本,它用來分離一個文檔的展現和數據
模板定義了placeholder和表示多種邏輯的tags來規定文檔如何展現
通常模板用來輸出HTML,但是Django模板也能生成其它基于文本的形式
讓我們來看看一個簡單的模板例子:
- <html>
- <head><title>Ordering notice</title></head>
- <body>
- <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>
- {% endif %}
- <p>Sincerely,<br />{{ company }}</p>
- </body>
- </html>
這個模板本質上是HTML,但是夾雜了一些變量和模板標簽:
1,用{{}}包圍的是變量,如{{person_name}},這表示把給定變量的值插入,如何指定這些變量的值我們即將說明
2,用{%%}包圍的是塊標簽,如{%if ordered_warranty%}
塊標簽的含義很豐富,它告訴模板系統做一些事情
在這個例子模板中包含兩個塊標簽:for標簽表現為一個簡單的循環結構,讓你按順序遍歷每條數據
if標簽則表現為邏輯的if語句
在這里,上面的標簽檢查ordered_warranty變量的值是否為True
如果是True,模板系統會顯示{%if ordered_warranty%}和{%endif%}之間的內容
否則,模板系統不會顯示這些內容
模板系統也支持{%else%}等其它邏輯語句
3,上面還有一個過濾器的例子,過濾器是改變變量顯示的方式
上面的例子中{{ship_date|date:"F j, Y"}}把ship_date變量傳遞給過濾器
并給date過濾器傳遞了一個參數“F j, Y”,date過濾器以給定參數的形式格式化日期
類似于Unix,過濾器使用管道字符“|”
Django模板支持多種內建的塊標簽,并且你可以寫你自己的標簽
使用模板系統
在Python代碼中使用模板系統,請按照下面的步驟:
1,用模板代碼創建一個Template對象
Django也提供指定模板文件路徑的方式創建Template對象
2,使用一些給定變量context調用Template對象的render()方法
這將返回一個完全渲染的模板,它是一個string,其中所有的變量和塊標簽都會根據context得到值
創建模板對象
最簡單的方式是直接初始化它,Template類在django.template模塊中,初始化方法需要一個參數
下面進入Python交互環境看看:
- >>> from django.template import Template
- >>> t = Template("My name is {{my_name}}.")
- >>> print t
你將看到如下信息
- <django.template.Template object at 0xb7d5f24c>
0xb7d5f24c每次都會改變,但是無所謂,它是Template對象的Python“identity”
在這本書中,我們會在Python的交互式會話環境中展示一些示例。當你看到三個大于號'>>>',就可以確定是在交互環境中了。
如果你從本書中拷貝代碼,記得不要拷貝這些大于號。
當你創建Template對象,模板系統會編譯模板代碼,并準備渲染
如果你的模板代碼有語法錯誤,調用Template()方法會觸發TemplateSyntaxError異常
- >>> from django.template import Template
- >>> t = Template('{%notatag%}')
- Traceback (most recent call last):
- File "<stdin>", line 1, in ?
- ...
- django.template.TemplateSyntaxError: Invalid block tag: 'notatag'
系統觸發TemplateSyntaxError異常可能出于以下情況:
1,不合法的塊標簽
2,合法塊標簽接受不合法的參數
3,不合法的過濾器
4,合法過濾器接受不合法的參數
5,不合法的模板語法
6,塊標簽沒關
渲染模板
一旦你擁有一個Template對象,你可以通過給一個context來給它傳遞數據
context是一個變量及賦予的值的集合,模板使用它來得到變量的值,或者對于塊標簽求值
這個context由django.template模塊的Context類表示
它的初始化函數有一個可選的參數:一個映射變量名和變量值的字典
通過context調用Template對象的render()方法來填充模板,例如:
- >>> from django.template import Context, Template
- >>> t = Template("My name is {{name}}.")
- >>> c = Context({"name": "Stephane"})
- >>> t.render(c)
- 'My name is Stephane.'
變量名必須以字母(A-Z或a-z)開始,可以包含數字,下劃線和小數點,變量名大小寫敏感
下面是一個模板編譯和渲染的例子,使用這章開始時的模板例子:
- >>> from django.template import Template, Context
- >>> raw_template = """<p>Dear {{ person_name }},</p>
- ...
- ... <p>Thanks for ordering {{ product }} from {{ company }}. It's scheduled to
- ... ship on {{ ship_date|date:"F j, Y" }}.</p>
- ...
- ... {% if ordered_warranty %}
- ... <p>Your warranty information will be included in the packaging.</p>
- ... {% endif %}
- ...
- ... <p>Sincerely,<br />{{ company }}</p>"""
- >>> t = Template(raw_template)
- >>> import datetime
- >>> c = Context({'person_name': 'John Smith',
- ... 'product': 'Super Lawn Mower',
- ... 'company': 'Outdoor Equipment',
- ... 'ship_date': datetime.date(2009, 4, 2),
- ... 'ordered_warranty': True})
- >>> t.render(c)
- "<p>Dear John Smith,</p>\n\n<p>Thanks for ordering Super Lawn Mower from Outdoor Equipment.
- It's scheduled to ship on April 2, 2009.</p>\n\n<p>Your warranty information will be included
- in the packaging.</p>\n\n\n<p>Sincerely,<br />Outdoor Equipment</p>"
讓我們來看看都做了些什么:
1,我們import Template和Context類,它們都在django.template模塊里面
2,我們把模板文本存儲在raw_template變量里,我們使用"""來構建string,它可以跨越多行
3,我們創建模板對象t,并給Template類的初始化函數傳遞raw_template變量
4,我們從Python的標準庫import datetime模塊,下面會用到它
5,我們創建一個context對象c,它的初始化函數使用一個映射變量名和變量值的字典
例如我們指定person_name的值為'John Smith',product的值為'Super Lawn Mower'等等
6,最后,我們調用模板對象的render()方法,參數為context對象c
這將返回渲染后的模板,將模板中的變量值替換并計算塊標簽的結果
如果你剛接觸Python,你可能會問為什么輸出中包含了新行字符'\n'而不是換行
這是因為Python交互環境中調用t.render(c)會顯示string的representation而不是string的值
如果你想看到換行而不是'\n',使用print t.render(c)即可
上面是使用Django模板系統的基礎,只是創建一個模板對象和context對象然后調用render()方法
同一個模板,多個context的情況:
一旦你創建了一個模板對象,你可以渲染多個context,例如:
- >>> 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
無論何時,你使用同一個模板來渲染多個context的話,創建一次Template對象然后調用render()多次會更高效
- # Bad
- for name in ('John', 'Julie', 'Pat'):
- t = Template('Hello, {{ name }}')
- print t.render(Context({'name': name}))
- # Good
- t = Template('Hello, {{ name }}')
- for name in ('John', 'Julie', 'Pat'):
- print t.render(Context({'name': name}))
Django的模板解析非常快,在后臺,大部分的解析通過一個單獨的對正則表達式的調用來做
這與基于XML的模板引擎形成鮮明對比,XML解析器比Django的模板渲染系統慢很多
Context變量查找
上面的例子中,我們給模板context傳遞了簡單的值,大部分是string,以及一個datetime.date
盡管如此,模板系統優雅的處理更復雜的數據結構,如列表,字典和自定義對象
在Django模板系統中處理復雜數據結構的關鍵是使用(.)字符
使用小數點來得到字典的key,屬性,對象的索引和方法
下面通過例子來解釋,通過(.)訪問字典的key:
- >>> 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)
- 'Sally is 43 years old.'
通過(.)來訪問對象的屬性:
- >>> 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)
- 'The month is 5 and the year is 1993.'
下面的例子使用一個自定義類:
- >>> from django.template import Template, Context
- >>> class Person(object):
- ... def __init__(self, first_name, last_name):
- ... self.first_name, self.last_name = first_name, last_name
- >>> t = Template('Hello, {{ person.first_name }} {{ person.last_name }}.')
- >>> c = Context({'person': Person('John', 'Smith')})
- >>> t.render(c)
- 'Hello, John Smith.'
小數點也可以用來調用列表的索引:
- >>> from django.template import Template, Context
- >>> t = Template('Item 2 is {{ items.2 }}.')
- >>> c = Contexst({'items': ['apples', 'bananas', 'carrots']})
- >>> t.render(c)
- 'Item 2 is carrots.'
負數的列表索引是不允許的,例如模板變量{{ items.-1 }}將觸發TemplateSyntaxError
最后小數點還可以用來訪問對象的方法,例如Python的string有upper()和isdigit()方法:
- >>> from django.template import Template, Context
- >>> t = Template('{{ var }} -- {{var.upper }} -- {{ var.isdigit }}')
- >>> t.render(Context({'var': 'hello'}))
- 'hello -- HELLO -- False'
- >>> t.render(Context({'var': '123'}))
- '123 - 123 - True'
注意,調用方法時你不能加括號,你也不能給方法傳遞參數
你只能調用沒有參數的方法,后面我們會解釋這些
總結一下,當模板系統遇到變量名里有小數點時會按以下順序查找:
1,字典查找,如foo["bar"]
2,屬性查找,如foo.bar
3,方法調用,如foo.bar()
3,列表的索引查找,如foo[bar]
小數點可以多級縱深查詢,例如{{ person.name.upper }}表示字典查詢person['name']然后調用upper()方法
- >>> from django.template import Template, Context
- >>> person = {'name': 'Sally', 'age': '43'}
- >>> t = Template('{{ person.name.upper }} is {{ person.age }} years old.')
- >>> c = Context({'person': person})
- >>> t.render(c)
- 'SALLY is 43 years old.'
關于方法調用
方法調用要比其他的查詢稍微復雜一點,下面是需要記住的幾點:
1,在方法查詢的時候,如果一個方法觸發了異常,這個異常會傳遞從而導致渲染失
敗,但是如果異常有一個值為True的silent_variable_failure屬性,這個變量會渲染成空string:
- >>> t = Template("My name is {{ person.first_name }}.")
- >>> class PersonClas3:
- ... def first_name(self):
- ... raise AssertionError, "foo"
- >>> p = PersonClass3()
- >>> t.render(Context({"person": p}))
- Traceback (most recent call last):
- ...
- AssertionError: foo
- >>> class SilentAssetionError(AssertionError):
- ... silent_variable_failure = True
- >>> class PersonClass4:
- ... def first_name(self):
- ... raise SilentAssertionError
- >>> p = PersonClass4()
- >>> t.render(Context({"person": p}))
- "My name is ."
2,方法調用僅僅在它沒有參數時起作用,否則系統將繼續查找下一個類型(列表索引查詢)
3,顯然一些方法有副作用,讓系統訪問它們是很愚蠢的,而且很可能會造成安全性問
題。
例如你有一個BankAccount對象,該對象有一個delete()方法,模板系統不應該允許做下面的事情
I will now delete this valuable data. {{ account.delete }}
為了防止這種狀況,可以在方法里設置一個方法屬性alters_data
如果設置了alters_data=True的話模板系統就不會執行這個方法:
- def delete(self):
- # Delete the account
- delete.alters_data = True
不合法的變量怎樣處理
默認情況下如果變量不存在,模板系統會把它渲染成空string,例如:
- >>> from django.template import Template, Context
- >>> t = Template('Your name is {{ name }}.')
- >>> t.render(Context())
- 'Your name is .'
- >>> t.render(Context({'var': 'hello'}))
- 'Your name is .'
- >>> t.render(Context({'NAME': 'hello'}))
- 'Your name is .'
- >>> t.render(Context({'Name': 'hello'}))
- 'Your name is .'
系統會靜悄悄地顯示錯誤的頁面,而不是產生一個異常,因為這種情況通常是人為的錯誤。
在現實情形下,一個web站點因為一個模板代碼語法的錯誤而變得不可用是不可接受的。
我們可以通過設置Django配置更改Django的缺省行為,第10章擴展模板引擎會我們會討論這個
玩玩Context對象
大多數情況下你初始化Context對象會傳遞一個字典給Context()
一旦你初始化了Context,你可以使用標準Python字典語法增減Context對象的items:
- >>> from django.template import Context
- >>> c = Context({"foo": "bar"})
- >>> c['foo']
- 'bar'
- >>> del c['foo']
- >>> c['foo']
- ''
- >>> c['newvariable'] = 'hello'
- >>> c['newvariable']
- 'hello'
Context對象是一個stack,你可以push()和pop()
如果你pop()的太多的話它將觸發django.template.ContextPopException:
- >>> c = Context()
- >>> c['foo'] = 'first level'
- >>> c.push()
- >>> c['foo'] = 'second level'
- >>> c['foo']
- 'second level'
- >>> c.pop()
- >>> c['foo']
- 'first level'
- >>> c['foo'] = 'overwritten'
- >>> c['foo']
- 'overwritten'
- >>> c.pop()
- Traceback (most recent call last):
- ...
- django.template.ContextPopException
第10章你會看到使用Context作為stack自定義模板標簽
模板標簽和過濾器基礎
我們已經提到模板系統使用內建的標簽和過濾器
這里我們看看常見的,附錄6包含了完整的內建標簽和過濾器,你自己熟悉那個列表來了解可以做什么是個好主意
if/else
{% if %}標簽計算一個變量值,如果是“true”,即它存在、不為空并且不是false的boolean值
系統則會顯示{% if %}和{% endif %}間的所有內容:
- {% if today_is_weekend %}
- <p>Welcome to the weekend!</p>
- {% else %}
- <p>Get back to work.</p>
- {% endif %}
{% if %}標簽接受and,or或者not來測試多個變量值或者否定一個給定的變量,例如:
- {% if athlete_list and coach_list %}
- Both athletes and coaches are available.
- {% endif %}
- {% if not athlete_list %}
- There are no athletes.
- {% endif %}
- {% if athlete_list or coach_list %}
- There are some athletes or some coaches.
- {% endif %}
- {% if not athlete_list or coach_list %}
- There are no athletes or there are some coaches.
- {% endif %}
- {% if athlete_list and not coach_list %}
- There are some athletes and absolutely no coaches.
- {% endif %}
{% if %}標簽不允許同一標簽里同時出現and和or,否則邏輯容易產生歧義,例如下面的標簽是不合法的:
- {% if athlete_list and coach_list or cheerleader_list %}
如果你想結合and和or來做高級邏輯,只需使用嵌套的{% if %}標簽即可:
- {% if athlete_list %}
- {% if coach_list or cheerleader_list %}
- We have athletes, and either coaches or cheerleaders!
- {% endif %}
- {% endif %}
多次使用同一個邏輯符號是合法的:
- {% if athlete_list or coach_list or parent_list or teacher_list %}
沒有{% elif %}標簽,使用嵌套的{% if %}標簽可以做到同樣的事情:
- {% if athlete_list %}
- <p>Here are the athletes: {{ athlete_list }}.</p>
- {% else %}
- <p>No athletes are available.</p>
- {% if coach_list %}
- <p>Here are the coaches: {{ coach_list }}.</p>
- {% endif %}
- {% endif %}
確認使用{% endif %}來關閉{% if %}標簽,否則Django觸發TemplateSyntaxError
for
{% for %}標簽允許你按順序遍歷一個序列中的各個元素
Python的for語句語法為for X in Y,X是用來遍歷Y的變量
每次循環模板系統都會渲染{% for %}和{% endfor %}之間的所有內容
例如,顯示給定athlete_list變量來顯示athlete列表:
- <ul>
- {% for athlete in athlete_list %}
- <li>{{ athlete.name }}</li>
- {% endfor %}
- </ul>
在標簽里添加reversed來反序循環列表:
- {% for athlete in athlete_list reversed %}
- ...
- {% endfor %}
- {% for %}標簽可以嵌套:
- {% for country in countries %}
- <h1>{{ country.name }}</h1>
- <ul>
- {% for city in country.city_list %}
- <li>{{ city }}</li>
- {% endfor %}
- </ul>
- {% endfor %}
系統不支持中斷循環,如果你想這樣,你可以改變你想遍歷的變量來使得變量只包含你想遍歷的值
類似的,系統也不支持continue語句,本章后面的“哲學和限制”會解釋設計的原則
{% for %}標簽內置了一個forloop模板變量,這個變量含有一些屬性可以提供給你一些關于循環的信息
1,forloop.counter表示循環的次數,它從1開始計數,第一次循環設為1,例如:
- {% for item in todo_list %}
- <p>{{ forloop.counter }}: {{ item }}</p>
- {% endfor %}
2,forloop.counter0類似于forloop.counter,但它是從0開始計數,第一次循環設為0
3,forloop.revcounter表示循環中剩下的items數量,第一次循環時設為items總數,最后一次設為1
4,forloop.revcounter0類似于forloop.revcounter,但它是表示的數量少一個,即最后一次循環時設為0
5,forloop.first當第一次循環時值為True,在特別情況下很有用
安徽新華電腦學校專業職業規劃師為你提供更多幫助【在線咨詢】