Django中template 使用
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.创建一个templatefrom django.template import Context, Templatet = Template('My name is {{ name }}')c = Context({'name':'zhang'})t.render(c)注:Template()构造出一个template对象,她接收一个原生template字符串,Context()函数接收一个字典,这个用于template对象的render()函数来渲染原生字符串注意:t.render()函数返回的是unicode字符串不是常用的字符串一个例子:# Badfor name in ('John', 'Julie', 'Pat'):t = Template('Hello, {{ name }}')print t.render(Context({'name': name}))# Goodt = 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.bar3.方法查阅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, Templatec = Context({'foo':'bar})c['foo']-> 'bar' 访问属性del c['foo'] ->删除fooc['foo']->出错c['hello'] = 'hello world'->赋值5.Template中的基本的Tag1.普通的条件判断: {% if %} {% else %} {% elseif %} {% endif %}补充:python中被认为为False的1.空list[]2.空tuple()3.空字典{}4.空字符串''5.零06.特殊对象None7.False8.定制的对象,自己定制了Boolean的行为,这个在Python的高级中使用9.其他的所有都是True2.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长度递减到1forloop.revcounter在以0索引为开否的对象中,以长度减一开始递减至0forloop.first当是第一次访问时,被设置为True,这个对于一些输出控制很有好处forloop.last当是最后一次访问时,被设置为Trueforloop.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通过格式化后输出