Chinaunix首页 | 论坛 | 博客
  • 博客访问: 26278823
  • 博文数量: 2065
  • 博客积分: 10377
  • 博客等级: 上将
  • 技术积分: 21525
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-04 17:50
文章分类

全部博文(2065)

文章存档

2012年(2)

2011年(19)

2010年(1160)

2009年(969)

2008年(153)

分类: Python/Ruby

2009-08-10 16:55:53

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 }}这个标签非常有用,可以做到不仅仅是覆盖父模板,而是在父模板基础上追加内容。当然也可以覆盖。

这就给了我们灵活性:既可以完全重写,也可以复用父模板,也可以在复用的基础上扩展。

不错的网站

1





阅读(1107) | 评论(0) | 转发(0) |
0

上一篇: django编码问题的解决

下一篇:php数组整理

给主人留下些什么吧!~~