1.template 使用
template不仅可以用来导出HTML,他可以用来做任何的
基于文本的处理
1.在交互模式下使用template
使用django的template时,他需要查找一个变量的
设置,叫:DJANGO_SETTINGS_MODULE,这个指向的是
当前的工作项目的settings.py文件,所以,要想在
交互模式下使用template,最好先通过
django-admin.py startproject mysite开启一个项目
然后进入mysite,运行python manage.py shell进入
交互模式,这样就自动的读取了DJANGO_SETTINGS_MODULE
变量所指定的配置文件
当然,你也可以直接运行python,然后只用内置函数再
设置该变量也可以
2.创建一个template
from django.template import Context, Template
t = Template('My name is {{ name }}')
c = Context({'name':'zhang'})
t.render(c)
注:Template()构造出一个template对象,她接收一个
原生template字符串,Context()函数接收一个字典,
这个用于template对象的render()函数来渲染原生字符串
注意:t.render()函数返回的是unicode字符串不是
常用的字符串
一个例子:
# 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}))
3.Context变量的查阅
>>> 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.'
这里使用字典来渲染template,可以使用点好"."来访问
其对象中包含的属性,非常简洁
同样的使用,可以用来访问对象的方法,属性,但访问
对象的方法时不能有括号,所以不能调用需要参数的方法
如:string的isdigit(),upper()这些方法可以的
>>> 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'
点查阅总结:
当template对象遇到点号时,按如下顺序进行查阅:
1.字典查阅 eg: foo['bar']
2.属性查阅 eg: foo.bar
3.方法查阅 eg: foo.bar()
4.list索引查阅 eg: foo[0] 没有证实成功
方法查阅:
1.如果方法在执行过程中有异常产生,如果在方法中有
一个变量silent_variable_failure设置为true,则该异常
不会输出,template会以空字符替代,如:
>>> 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}))
u'My name is .'
4.Context对象访问
当初始化Context为字典时,可以像字典一样访问context中的属性,赋值
from django.template import Context, Template
c = Context({'foo':'bar})
c['foo'] -> 'bar' 访问属性
del c['foo'] ->删除foo
c['foo'] ->出错
c['hello'] = 'hello world' ->赋值
5.Template中的基本的Tag
1.普通的条件判断: {% if %} {% else %} {% elseif %} {% endif %}
补充:
python中被认为为False的
1.空list []
2.空tuple ()
3.空字典 {}
4.空字符串 ''
5.零 0
6.特殊对象 None
7. False
8.定制的对象,自己定制了Boolean的行为,这个在Python的高级中使用
9.其他的所有都是True
2.for语句
{% for item in todo_list %}
<p>{{ forloop.counter }}: {{ item }}</p>
{% endfor %}
注:for中,
forloop.counter 在迭代过程中从1递增到list的长度
forloop.counter0 在是0索引的序列中是以0递增的list的长度减一
forloop.revcounter 在迭代过程中从list长度递减到1
forloop.revcounter 在以0索引为开否的对象中,以长度减一开始递减至0
forloop.first 当是第一次访问时,被设置为True,这个对于一些输出
控制很有好处
forloop.last 当是最后一次访问时,被设置为True
forloop.parentloop.counter 父级的循环计数器
3.ifequal/ifnotequal
{% ifequal user currentuser %}
<h1>Welcome!</h1>
{% endifequal %}
4.注释
{# This is a comment #}
5.过滤器filter
{{ name|lower }}
过滤器的原理是管道pipe,即第一个命令的输出是第二个命令的输入,这里将name的输出
转换为小写
{{ my_list|first|upper }}
这里将my_list的第一个元素转换为大写输出
{{ pub_date|date:"F j, Y" }}
这里将put_date的输出给date,date通过格式化后输出