django背景变量的查找

在到目前为止的例子中,我们通过 context 传递的简单参数值主要是字符串,还有一个
datetime.date 范例。
然而,
模板系统能够非常简洁地处理更加复杂的数据结构,
例如 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)
'Sally is 43 years old.'
1
同样,
也可以通过句点来访问对象的属性。
比方说, 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)
'The month is 5 and the year is 1993.'
下例使用了一个自定义类:
>>> from django.template import Template, Context
59
http://djangobook.py3k.cn/
第四章 Django 模板系统
>>> 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.'
句点还用于调用对象的方法。
例如,
每个 Python 字符串都有 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'
注意你不能在方法调用中使用圆括号。而且也无法给该方法传递参数;你只能调用不需参数
的方法。(我们将在本章稍后部分解释该设计观。)
最后,句点也可用于访问列表索引,例如:
>>> from django.template import Template, Context
>>> t = Template('Item 2 is {{ items.2 }}.')
>>> c = Context({'items': ['apples', 'bananas', 'carrots']})
>>> t.render(c)
'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)
'SALLY is 43 years old.'


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值