一:模板的继承(extends)
{% block name %}
{ %endblock%}
母版:
{% block BLOCKNAME%}
{% endbock}
子继承
{% extends “name” %}
{% block BLOCKNAME%}
内容
{% endbock}
母版
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.pagehead{
background: green;
}
</style>
{% block css %}
{% endblock %}
</head>
<body>
<div class="pagehead">Welcome</div>
<div class="content">
{% block content %}
{% endblock %}
</div>
<script src="/static/jquery-1.12.4.js"></script>
{% block js %}
{% endblock %}
</body>
</html>
子模板继承:
{% extends "master.html" %} #继承母版
{% block title %} #对应的block中
tp1
{% endblock %}
{% block content %}
<h1>hello ,tp1</h1>
{{ name }}
{% endblock %}
{% block css %}
<style>
.pagehead{
background: red;
}
</style>
{% endblock %}
二、模板的包含 {% include name %}
django对tag模板也能够熏染
tags.html
<h1 class="logo_tit">
<a href="//www.jd.com" class="logo_tit_lk" clstag="h|keycount|head|logo_01">京东</a>
<h1>{{ str1 }}</h1>
</h1>
def tp1(request, *args, **kwargs):
name='tp111'
return render(request,"tp1.html",{"name":name,"str1":"tags for templates"})
tp1.html ({% includ “tags.html”%})
{% block content %}
<h1>hello ,tp1</h1>
{{ name }}
{% include "tags1.html" %}
{% endblock %}
三、DJango提供的自定义模板方法
django将python的函数放在模板中进行处理
<h1 class="logo_tit">
<a href="//www.jd.com" class="logo_tit_lk" clstag="h|keycount|head|logo_01">京东</a>
<h1>{{ str1|truncatechars:'12'}}</h1>
</h1>
自定义simple_tag
-
自定义函数
simple_taga. app下创建templatetags目录 b. 任意xxoo.py文件 c. 创建template对象 register d. @register.simple_tag def func(a1,a2,a3....) return "asdfasd" e. settings中注册APP f. 顶部 {% load xxoo %} g. {% 函数名 arg1 arg2 %} 缺点: 不能作为if条件 优点: 参数任意
templatetags/xxoo.py
from django import template
register=template.Library()
@register.simple_tag
def hello(a,b):
return a+b
template/tp1.html
{% block content %}
<h1>hello ,tp1</h1>
{{ name }}
{% hello 2 3%} #调用了xxoo方法
{% include "tags1.html" %}
{% endblock %}
定义filter自定义
filter
a. app下创建templatetags目录
b. 任意xxoo.py文件
c. 创建template对象 register
d.
@register.filter
def func(a1,a2)
return "asdfasd"
e. settings中注册APP
f. 顶部 {% load xxoo %}
g. {{ 参数1|函数名:"参数二,参数三" }} {{ 参数1|函数名:数字 }}
缺点:
最多两个参数,不能加空格
优点:
能作为if条件
from django import template
register=template.Library()
@register.simple_tag
def hello(a,b):
return a+b
@register.filter
def fil(a,b):
return a+b
html中引用
{% extends "master.html" %}
{% load xxoo %}
{% block title %}
tp1
{% endblock %}
{% block content %}
<h1>hello ,tp1</h1>
{{ name }}
{% hello 2 3%}
{{ 'a--a'|fil:'b' }}
{% if 1|fil:0 %}
<h1>嵌套if用法</h1>
{% endif %}
{% include "tags1.html" %}
{% endblock %}