免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3447 | 回复: 0
打印 上一主题 下一主题

Django模板系统学习整理 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-08-10 16:55 |只看该作者 |倒序浏览

                Django模板系统——模板的继承 extends
include  逆向 extends

一、定义基础模板,在html内容中定义多个block块,block由子模板引用同名block块,来决定是否替换这些部分
{% block title %}一些内容,这里可不填{% endblock %}
{% block content %}一些内容,这里可不填{% endblock %}
{% block footer %}一些内容,这里可不填{% endblock %}
这里 title content footer 不是变量,名字自定义

二、子模板的引用方式
{% extends "base.html" %}
{% block title %}The current time{% endblock %}
{% block content %}It is now {{ current_date }}.{% endblock %}
第一句是固定的格式,必须为模板中的第一个模板标记
extends的参数一般为字符串,也可为变量
可带路径,相对路径,以 TEMPLATE_DIRS 的模板目录 为基准
子模板决定替换的block块,无须关注其它部分,没有定义的块即不替换,直接使用父模板的block块

三、引用上级代码块在其基础上进行一些修改 {{ block.super }}
{% block footer %}
{{ block.super }}
AAAAA
{% endblock %}
Django模板系统——模板包含另一模板 include
使用模板加载API机制之后,可用的包含其它模板标签
{% include 'nav.html' %}
{% include "nav.html" %}
可带路径,相对路径,以 TEMPLATE_DIRS 的模板目录 为基准
{% include 'includes/nav.html' %}
可使用变量名
{% include template_name %}
包含的变量都会统一处理,不区分是第几层模板
Django模板系统——模板加载API
一、设置配置文件
在 settings.py 中设置TEMPLATE_DIRS,添加路径元素,绝对路径,用 / 号路径分隔符,末尾不含 / 号
建议 在项目下使用 templates 目录放置模板文件
TEMPLATE_DIRS 中允许多个路径,加载模板时会按这个顺序搜索模板文件
一个技巧:
import os.path
TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
)

二、用模板加载API,成功了
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
import datetime
def current_datetime4(request):
  now = datetime.datetime.now()
  t = get_template('current_datetime4.html')
  html = t.render(Context({'current_date': now}))
  return HttpResponse(html)

二的二、模板文件的路径可以放在子目录中调用
t = get_template('dateapp/current_datetime4.html')

三、更精简的加载,直接查找文件,给出数据,并返回结果
from django.shortcuts import render_to_response
import datetime
def current_datetime5(request):
    now = datetime.datetime.now()
    return render_to_response('current_datetime5.html', {'current_date': now} )

四、locals() 技巧,因为locals()是个字典,直接赋值给变量,把locals()提交给模板API即可
from django.shortcuts import render_to_response
import datetime
def current_datetime6(request):
    current_date = datetime.datetime.now()
    return render_to_response('current_datetime6.html', locals())
Django的{{ block.super }}模板标签
Django模板中{{ block.super }}这个标签非常有用,可以做到不仅仅是覆盖父模板,而是在父模板基础上追加内容。当然也可以覆盖。
这就给了我们灵活性:既可以完全重写,也可以复用父模板,也可以在复用的基础上扩展。
http://hi.baidu.com/django_pinax  不错的网站
1
               
               
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/84280/showart_2023636.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP