主模板:master.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %} {% endblock %}</title> #替换位置加{% block title %}{% endblock %} <link rel="stylesheet" href="/static/commons.css"> <style> #全局css .pg-header{ height: 48px; background-color: seashell; color: green; } </style>
{% block css %} {% endblock%} #自定义css 由继承模板时加入 </head> <body> <div class="pg-header">管理界面</div> {% block content %} {% endblock %} #替换位置 <script src="/static/jquery.js"></script> #全局js
{% block js %} {% endblock %} #自定义js 由继承模板时加入 </body> </html>
# 继承模板:
{% extends 'master.html' %} #继承模板需要添加,继承的模板来自master.html {% block title %}用户管理{% endblock %} #替换模板中title的位置 {% block css %}<style>...</style>{% endblock %} #自定义css {% block content %} #替换模板中content的位置 <h1>用户管理</h1> <ul> {% for u in user_list %} <li>{{ u }}</li> {% endfor %} </ul> {% endblock %}
{% block js %}<script src="..."></script>{% endblock %} #自定义js
#模板导入:
# 需要导入的模板 tag.html <form action=""> <input type="text"> <input type="submit"> </form>
{% extends 'master.html' %}
{% block title %}用户管理{% endblock %}
{% block content %}
{% include "tag.html" %} #导入模板html
{% endblock %}
继承 :
{% extends '模板.html' %}
{% include "模板.html" %}
引用:
{% block 模板标题 %}{% endblock %}
关于自定义模板--simple_tag
ooxx.py
from django import template #导入模板类 from django.utils.safestring import mart_safe #给simple_tag打标记 register = tmplate.Librarry() #固定写法必须加,创建特template对象 @register.simple_tag #加simple_tag的装饰器 def houyafan(a1,a2): #返回网页的函数 return a1 + a2
{% load ooxx.py %} #导入simple_tag
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% houyafan 3 5 %} #调用simple_tag函数houyafan()返回 3+5=8 </body> </html>
注:需要在app01下创建一个文件夹名字必须是: templatetags
再在templatetags下面建立py文件在py文件中写以上Python代码
建立步骤:
simple_tag---filter
@register.filter #使用filter装饰器 def check(a1, a2): return a1 + a2
<body> {{ "zhangjian"|check:"ZJ" }} #跟django自带的filter一样 例如:{{ name | upper }}
</body>
输出:
fliter使用的场景:
{% if {{ “xx” |check :"yy"}} %}
优缺点对比: