继承
① extends用法:只继承一个模版
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="/static/commons.css" /> <style> .pg-header{ height: 50px; background-color: seashell; color: green; } </style> {% block css %}{% endblock %} </head> <body> <div class="pg-header">小男孩管理</div> {% block content %}{% endblock %} <div class="pg-footer"></div> <script src="/static/jquery.js"></script> {% block js %}{% endblock %} </body> </html>
{% extends ‘master.html‘ %} <!--继承模版-->
{% block title %}DIY网站{% endblock %} <!--继承模版里面的块-->
{% block content %}
<h1>用户管理</h1>
<ul>
{% for i in u %}
<li>{{ i }}</li>
{% endfor %}
</ul>
{% endblock %}
{% block css %}
<style>
body{
background-color: red;
}
</style>
{% endblock %}
def tpl1(request): user_list = [1,2,3,4] return render(request,‘tpl1.html‘,{‘u‘:user_list})

②include用法 :(可以多个重复操作)
<form>
<input type="text"/>
<input type="submit"/>
</form>
{% extends ‘master.html‘ %} <!--继承模版-->
{% block title %}DIY网站{% endblock %} <!--继承模版里面的块-->
{% block content %}
<h1>用户管理</h1>
<ul>
{% for i in u %}
<li>{{ i }}</li>
{% endfor %}
</ul>
{% include ‘tag.html‘%} <!--导入单独组件-->
{% include ‘tag.html‘%}
{% for i in u %} <!--循环4次-->
{% include ‘tag.html‘%}
{% endfor %}
{% endblock %}
{% block css %}
<style>
body{
background-color: red;
}
</style>
{% endblock %}

③自定义simple_tag,filter
a、在app中创建templatetags模块
b、创建任意 .py 文件,如:daly.py
from django import template register = template.Library() @register.simple_tag def hanshu(a1,a2): return a1 * a2
注:
simple_tag 中
@register.simple_tag
def func(a1,a2,a3....)
filter中:
@register.filter
def func(a1,a2)
c、在使用自定义simple_tag的tpl2.html文件中导入之前创建的 daly.py 文件名
{% load daly %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ name}}
{{ name|lower}}
{% hanshu 2 6 %} <!--对应daly.py中的hanshu-->
</body>
</html>
注:
simple_tag 中:
{% 函数名 a1 a2 a3... %}
缺点:不能作为if条件
优点:参数任意
filter中:
{{ a1|函数名:"a2,a3" }} {{a1|函数名:数字 }}
缺点:最多两个参数,不能加空格:
优点:能作为if条件
d、在settings中配置当前app,不然django无法找到自定义的simple_tag
INSTALLED_APPS = [ ‘django.contrib.admin‘, ‘django.contrib.auth‘, ‘django.contrib.contenttypes‘, ‘django.contrib.sessions‘, ‘django.contrib.messages‘, ‘django.contrib.staticfiles‘, ‘app01‘, ]
e、views.py代码
def tpl2(request): name = ‘abcABC‘ return render(request,‘tpl2.html‘,{‘name‘: name })

原文:https://www.cnblogs.com/dalyday/p/8991234.html