目录
1、异常处理对象的silent_variable_failure 属性
一、模板系统的基本概念
1、模板的概念
用 Django的模板系统 (Template System)来实现将页面的设计和Python的代码分离,会更干净简洁更容易维护
模板是一个文本,用于分离文档 的表现形式和内容。 模板定义 了占位符以及各种用于规范文档该如何显示的各部分基本逻辑(模板标签)。
2、模板系统的使用
基本原则
(1)Django可以用原始的模板代码字符串创建一个Template 对象
(2)Django也可以用指定模板文件路径的方式来创建 Template 对象;
(3)创建变量context。它将返回一个基于模板的展现字符串,模板中的变量和标签会被context值替换。
(4)调用模板对象的render方法,变量context传给模板
基本过程
(1)转到project目录(在之前由 django-admin startproject 命令创建), 输入命令 python manage.py shell 启动交互界面
(2)创建模板,然后对模板进行渲染
简单实例
>>> from django.template import Template, Context
>>> raw_template = """<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>
...
... {% 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>"""
>>> t = Template(raw_template)
>>> import datetime
>>> c = Context({'person_name': 'John Smith',
... 'company': 'Outdoor Equipment',
... 'ship_date': datetime.date(2009, 4, 2),
... 'ordered_warranty': False})
>>> t.render(c)
逐步分析:
(1)把模板原始文本保存到变量 raw_template 。注意到我们使用了三个引号来标识这些文本, 因为这样可以包含多行
(2)创建了一个模板对象 t ,把 raw_template 作为 Template 类构造函数的参数;
(3)创建一个 Context 对象 c 。Context 构造的参数是Python 字典数据类型。我们指定参数 person_name 的值是 'JohnSmith' , 参数company 的值为 ‘Outdoor Equipment‟ .引入datetime 模块等等。
(4)最后,在模板对象上调用 render() 方法,传递 context参数给它。这是返回渲染后的模板的方法
(5)为什么输出里有回车换行的字符('\n' )而不是显示回车 换行? 因为这是Python交互解释器的缘故:调用 t.render(c) 返回字符串,解释器缺省显示这些字符串的真实内容呈现 ,而不是打印这个变量的值。 要显示换行而不是 ‘\n’ ,使用 print 语句: print(t.render(c)) 。
二、深度变量的查找(点号引用)
在 Django 模板中遍历复杂数据结构的关键是句点字符 (.)。
1、向模板传递一个 Python 字典
通过一个句点,实现字典键访问该字典的值
2、向模板传递一个 Python 对象
通过句点来访问对象的属性
3、引用对象的方法。
例如,每个 Python 字符串都有upper() 和 isdigit() 方法,你在模板中可以使用同样的句点语法来调用它们
注意这里调用方法时并没有使用圆括号,而且也无法给该方法传递参数,你只能调用不 需参数的方法。
4、访问列表索引
通过【列表】.index的形式来实现通过索引访问列表
5、句点查找规则总结
• 字典类型查找(比如 foo[“bar”] );
• 属性查找(比如 foo.bar);
• 方法调用(比如 foo.bar() );
• 列表类型索引查找(比如 foo[bar] )。
三、方法调用行为
1、异常处理对象的silent_variable_failure 属性
如 果 某 方 法 抛 出 一 个 异 常 , 除 非 该 异 常 有 一 个 silent_variable_failure 属性并且值为 True ,否则的话它将被传播。如果异常被传播,模板里的指定变量会被置为空字符串
>>>from django.template import Template, Context
>>> t = Template("My name is {{ person.first_name }}.")
>>> class PersonClass3:
... def first_name(self):
... raise AssertionError("foo“)
>>> p = PersonClass3()
>>> t.render(Context({"person": p}))
Traceback (most recent call last):
...
AssertionError: foo
>>> class SilentAssertionError(AssertionError):
... silent_variable_failure = True
>>> class PersonClass4:
... def first_name(self):
... raise SilentAssertionError
>>> p = PersonClass4()
>>> t.render(Context({"person": p}))
'My name is .'
2、delete方法的 alters_data 函数属性
例如,你的一个 BankAccount 对象有一个 delete() 方法。 如果某个模板中包含 了像 {{ account.delete }}这样的标签,其中“ account” 又是BankAccount 的一 个实例,请注意在这个模板载入时,account对象将被删除。要防止这样的事情发生,必须设置该方法的 alters_data 函数属性。那么在模板载入时, delete()方法将不会被执行。 它将静静地错误退出。
def delete(self):
delete.alters_data = True
四、如何处理无效变量
默认情况下,如果一个变量不存在,模板系统会把它展示为空字符串,不做任何事情来表示失败
>>>from django.template import Template, Context
>>>t = Template('My name is {{name }}.')
>>>t.render(Context({'Name':'lll'}))
My name is .
五、上下文(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'