模板设计的两个要点,第一显示和逻辑要分离,不要把python嵌入到html里面,这是很糟糕的设计,django就用template和view的分层完成这样的设计。第二,可复用要抽出来,这也是普遍编程的设计逻辑,django允许parent template,这样从实际提供了模板重复设计的语法支持。
django模板从功能上也有一些限制,不能跑python代码,不能修改变量,这也是django要把显示和逻辑分离的设计原则决定的,所以我们使用的时候尽量避免这样的需求。
django响应请求的过程:
1. 浏览器发出一个url请求
2. patterns利用正则表达式来解析url
3. 解析出来的url,调用对因的view, view加载模板,构造context,送给模板显示。
django template语法概要。
1. context, 用字典封装的模板即将使用到的一系列的参数的列表,说道底就是view传给template的参数数值。
def detail(request):
c = Context({'fav_color': 'blue'})
t = Template("My favorite color is {{ fav_color }}.")
return HttpResponse(t.render(c))
2. 变量, My favorite color is {{ color }}.
3. filter 对变量输出进行规范的一组函数 My favorite color is {{ color|upper }}.
4. tags, template的语法标签。
{% ifequal color 'blue' %}
Wow, you like blue!
{% else %}
Why don't you like blue?
{% endifequal %}
5. comments
注释一行:{# Remember to move this down the page later #}
注释多行:
{% comment %}
My comment
is more than
one line long
{% endcomment %}