国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Django框架中方法的訪問和查找

2019-11-25 17:11:08
字體:
來源:轉載
供稿:網友

在 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.year1993>>> d.month5>>> d.day2>>> 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.'

這個例子使用了一個自定義的類,演示了通過實例變量加一點(dots)來訪問它的屬性,這個方法適用于任意的對象。

>>> 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)u'Hello, John Smith.'

點語法也可以用來引用對象的* 方法*。 例如,每個 Python 字符串都有 upper() 和 isdigit() 方法,你在模板中可以使用同樣的句點語法來調用它們:

>>> from django.template import Template, Context>>> t = Template('{{ var }} -- {{ var.upper }} -- {{ var.isdigit }}')>>> t.render(Context({'var': 'hello'}))u'hello -- HELLO -- False'>>> t.render(Context({'var': '123'}))u'123 -- 123 -- True'

注意這里調用方法時并* 沒有* 使用圓括號 而且也無法給該方法傳遞參數;你只能調用不需參數的方法。 (我們將在本章稍后部分解釋該設計觀。)

最后,句點也可用于訪問列表索引,例如:

>>> 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``

Python 列表類型

一點提示: Python的列表是從0開始索引。 第一項的索引是0,第二項的是1,依此類推。

句點查找規則可概括為: 當模板系統在變量名中遇到點時,按照以下順序嘗試進行查找:

  •     字典類型查找 (比如 foo["bar"] )
  •     屬性查找 (比如 foo.bar )
  •     方法調用 (比如 foo.bar() )
  •     列表類型索引查找 (比如 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)u'SALLY is 43 years old.'

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 沿河| 绥滨县| 高雄市| 嘉善县| 赞皇县| 松溪县| 安福县| 嵊泗县| 吴忠市| 大新县| 盖州市| 商都县| 龙口市| 囊谦县| 读书| 松原市| 杭州市| 丰顺县| 崇阳县| 长沙县| 抚州市| 肃南| 合水县| 会泽县| 太和县| 阳城县| 临潭县| 浦城县| 龙门县| 徐水县| 普宁市| 东明县| 平度市| 乡城县| 天津市| 海晏县| 慈利县| 上犹县| 府谷县| 诏安县| 红桥区|