Posted on 2006-11-28 20:27 
pts 阅读(275) 
评论(0)  编辑  收藏  所属分类: 
Django 
			 
			
		 
		
		DjangoBook note 
模板 
1、用 html 文件保存,设计的变量用 {{value_name}} 填充 
2、需 from django.template import Template,Context 导入库 
3、t=Template( 模板文件名 ) 
 c=Context( 模板变量内容 ) 
 t.render(c)# 可以输出模板内容 
4、   下面这段不理解什么意思 
 To prevent this, set a function attribute alters_data on the method. The template system won ’ t execute a method if the method has alters_data=True set. For example: 
 def delete(self): 
  # Delete the account 
 delete.alters_data = True 
5、 Context 对象支持 push()/pop() 方法 
6、 模板文件中的标签: 
 没有 elseif; 
 For 循环中没有 break 和 continue 
 For 循环中的几个属性: 
    forloop.counter     # 当前循环的次数,从 1 开始 
    forloop.counter0    # 当前循环的次数,从 0 开始 
    forloop.revcounter        # 当前循环剩余次数,从总循环次数递减 
    forloop.revcounter0       # 当前循环剩余次数,从总循环次数 -1 递减 
    forloop.first             #boolean 值,如果为第一次循环,值为真 
    forloop.last              # 同上 
    forloop.parentloop        # 引用父循环的 forloop 对象 
 ifequal A B  # AB 只能是模板变量、字符串、数字 
    pass #如果 A B 相等则执行 
 else 
    pass #否则执行 
 endifequal 
 {#   #}      #注释 
 {{A|B:”s”}}         # 对 A 执行 B 过滤, B 过滤可以有参数 
   几个过滤器: 
   addslashes    加反斜杠 
   Date          格式化日期为字符串 
   escape        转换为网页编码 
   length        长度 
7、 模板不能建立一个变量或者改变一个变量的值;不能调用原生的 python 代码 
8、 在 setting.py 中制定模板文件存放的目录( EMPLATE_DIRS ),例: 
 TEMPLATE_DIRS = ( 
  '/home/django/mysite/templates', 
 ) 
 不要忘了最后的逗号,除非你将序列()换成列表 [] ,但效率会降低;目录用 / 间隔 
9、 使用模板: 
 from django.shortcuts import render_to_response
 import datetime
		 def current_datetime(request):
  now = datetime.datetime.now()
 return render_to_response('current_datetime.html', {'current_date': now})
 可以将填充到模板的变量换为locals(),但性能会有所下降,如
 def current_datetime(request):
  current_date = datetime.datetime.now()
    return render_to_response('current_datetime.html', locals())
10、如果要引用设定的模板目录中子目录的模板文件 ; 
 t = get_template('dateapp/current_datetime.html')
11、模板可嵌套,模板文件名可用变量 
 {% include 'includes/nav.html' %}
 {% include template_name %}
12、模板继承,使用 extends 和一个特殊的标签 block ,例: 
 #base.html
 <head>
 <title> 
  {% block title %}标题{% endblock %}
 </title>
 </head>
 <body> 
 {% block content %}内容{% endblock %}
 {% block footer %} 页尾{% endblock %}
 </body>
 </html>
  下面的模板继承自 base.html 
 {% extends "base.html" %}     #这一行必须是第一个模板标签行 
 {% block title %} 我的标题 {% endblock %} 
 {% block content %} 
  <p> 我的内容 </p> 
 {% endblock %}   #不一定要重新定义父模板中的每个模板块 
 通过 block.super 引用父模板块内容