基础部分
模板是一个文档或者说一个普通的python字符串由Django模板语言标记而成。一个模板语言可以包括block标签或者是变量。
一个block标签是一个处于模板中的标记,能过完成一些事情。
Block的定义看起来有点模糊,这是django开发团队有意为之的。比如一个block标签即可以用来输出内容;也可以被当做一个控制结构(比如if声明或者是for循环)从数据库中抓去数据;或者是通往另一个模板的入口。
Block标签由”{%”和”%}”组成。
比如一个模板有如下标签
{% if is_logged_in%}Thanksfor logging in!{%else %}Pleaselog in.{%endif %}
变量用于是在模板里输出一个值的符号。
变量标签由”{{”和”}}”组成。
比如:
My first name is {{first_name}}. Mylast name is{{ last_name}}.
一个Context是指一个传入模板的由“变量名”到“变量值”的映射。
(原文:A context is a “variable name” -> “variable value” mapping thatis passed to a template.)
一个模板通过变量值来填补context中对应变量的“空缺”(译者注:像填空一样吧)和执行block标签来完成一个context的渲染。
使用模板系统
Template类
在django中使用模板系统是一个两部过程:
首先,你将一个未经处理的模板代码编译成一个template对象。
然后,你调用Template中的render()方法,并赋予其一个context。
编译一个字符串
创建一个Template对象最简单的方法就是直接初始化它。这个类位于django.template.Template中。其构造器需要一个参数——一个未经处理的模板代码。
>>> fromdjango.template importTemplate
>>> t
>>> print(t)
<django.template.Template instance>
幕后
及时这个处理非常迅速。大多数处理在两个表达式之间的短暂地、常规地的调用时发生。
渲染一个context
Render
一旦你有一个编译过的Template对象,你就能用它渲染一个context或者操作多个context。Context类存在于django.template.Context,需要两个参数(可选的)来完成构造:
n 一个带有name和对应value的字典
n 现用应用的名字,这个应用的名字用于帮助解决URL的命名空间(Reversingnamespaced URLs)。如果你不使用命名空间化过(namespaced)的URL,你可以忽略这个参数
>>> fromdjango.template importContext,Template
>>> t
>>> c= Context({"my_name":"Adrian"})
>>> t.render(c)
"My name is Adrian."
>>> c= Context({"my_name":"Dolores"})
>>> t.render(c)
"My name is Dolores."
变量及查询
n 字典查询。比如:foo[“bar”]
n 属性查询。比如:foo.bar
n 列表查询。比如foo[bar]
注意:像{{ foo.bar }} 中的“bar”在模板标记中将会被当做一个字符串,而非变量bar的值,当bar在模板的context中存在的话。
模板系统将会采用以上3中查询中首先生效的那个查询方式。这是一个短循环逻辑。比如:
>>> fromdjango.template importContext, Template
>>> t
>>> d:
>>> t.render(Context(d))
"My name is Joe."
>>> classPersonClass:pass
>>> p= PersonClass()
>>> p.first_name= "Ron"
>>> p.last_name= "Nasty"
: p}))
"My name is Ron."
>>> t
>>> c,
>>> t.render(c)
"Thefirst stooge in the list is Larry."
如果一个变量的任何一个部分是可调用的,模板会尽量去调用它,比如:
>>> classPersonClass2:
… def
… return"Samantha"
>>> t
: PersonClass2}))
"Myname is Samantha."
属性,并且它的值为true。如果异常的确有silent_variable_failure=True,则变量会渲染成空字符串。
比如:
>>> t
>>> classPersonClass3:
… def
… raise
>>> p= PersonClass3()
: p}))
Traceback (most recent call last):
…
AssertionError: foo
>>> classSilentAssertionError(Exception):
… silent_variable_failure=True
>>> classPersonClass4:
… def
… raiseSilentAssertionError
>>> p= PersonClass4()
: p}))
"Myname is ."
希望你灰暗的心情在此刻明亮起来,去迎接美好的明天!