第五篇.模版层
一.模版简介
pass
二.模版语法之变量
在Django模版中遍历复杂数据结构的关键是句点字符,语法:{{变量名}}
views文件
from django.shortcuts import render from django.http import JsonResponse # Create your views here. def index(request): name='lqz' age=18 l1=[1,2,'lqz','egon'] ll2=[] dic2={} tu=(1,2,3) dic={'name':'lqz','age':18,'ll':[1,2,4]} #函数 def test(): print() return '诺天王 dsb' #在模板上相当于执行该函数,并打印 print(test()) #类和对象 class Person(): def __init__(self,name,age): self.name=name self.age=age def get_name(self): return self.name @classmethod def cls_test(cls): return 'cls' @staticmethod def static_test(): return 'static' lqz=Person('lqz',18) egon=Person('egon',18) person_list=[lqz,egon] person_dic={'lqz':lqz} return render(request,'index.html',locals())
html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <hr> <h1>模板语言之变量</h1> <p>字符串:{{ name }}</p> <p>数字:{{ name }}</p> <p>列表:{{ ll }}</p> <p>元祖:{{ tu }}</p> <p>字典:{{ dic }}</p> <p>函数:{{ test }}</p> {#对象内存地址#} <p>对象:{{ lqz }}</p> <p>列表套对象{{ person_list }}</p> <p>字典套对象{{ person_dic }}</p> </body> </html>
urls文件
from django.conf.urls import url from django.contrib import admin from app03 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index/$',views.index) ]
三.模版之深度查询
深度查询统一用句点符
views.py文件
from django.shortcuts import render from django.http import JsonResponse # Create your views here. def index(request): name='lqz' age=18 ll=[1,2,'lqz','egon'] ll2=[] dic2={} tu=(1,2,3) dic={'name':'诺天王','age':18,'ll':[1,2,4]} #函数 def test(): print() return '诺天王 dsb' #在模板上相当于执行该函数,并打印 print(test()) #类和对象 class Person(): def __init__(self,name,age): self.name=name self.age=age def get_name(self): return self.name @classmethod def cls_test(cls): return 'cls' @staticmethod def static_test(): return 'static' #模板里不支持带参数 def get_name_cs(self): return self.name lqz=Person('lqz',18) egon=Person('egon',18) person_list=[lqz,egon] person_dic={'lqz':lqz} return render(request,'index.html',locals())
html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <hr> <h1>深度查询</h1> <p>列表第0个值:{{ ll.0 }}</p> <p>列表第三个值:{{ ll.3 }}</p> <p>字典取值:{{ dic.name }}</p> <p>字典取值列表:{{ dic.ll }}</p> <p>对象取数据属性{{ lqz.name }}</p> <p>对象取绑定给对象的函数属性:{{ lqz.get_name }}</p> <p>对象取绑定给类的函数属性:{{ lqz.cls_test }}</p> <p>对象取静态方法:{{ lqz.static_test }}</p> <p>把对象列表中egon年龄取出来:{{ person_list.1.age }}</p> {#拓展:不能调有参数的方法#} <p>字符串的方法:{{ name.upper }}</p> </body> </html>
urls文件
同上
四.模版之过滤器
常用方法
views.py文件
from django.shortcuts import render from django.http import JsonResponse # Create your views here. def index(request): name = 'lqz' age = 18 ll = [1, 2, 'lqz', 'egon'] ll2 = [] dic2 = {} tu = (1, 2, 3) dic = {'name': '诺天王', 'age': 18, 'll': [1, 2, 4]} # 函数 def test(): print() return '诺天王 dsb' # 在模板上相当于执行该函数,并打印 print(test()) # 类和对象 class Person(): def __init__(self, name, age): self.name = name self.age = age def get_name(self): return self.name @classmethod def cls_test(cls): return 'cls' @staticmethod def static_test(): return 'static' # 模板里不支持带参数 def get_name_cs(self): return self.name lqz = Person('lqz', 18) egon = Person('egon', 18) person_list = [lqz, egon] person_dic = {'lqz': lqz} file_size = 8888888 import datetime ctim = datetime.datetime.now() h1 = '<h1>你好</h1>' script = '<script>alert(111)</script>' return render(request, 'index.html', locals())
html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <hr> <h1>模板语言之过滤器</h1> <p>统计字符长度{{ name|length }}</p> <p>统计列表长度{{ ll|length }}</p> <p>过滤器之默认值{{ ll2|default:'没有值' }}</p> <p>过滤器之filesizeformat--1:{{ 8888888888|filesizeformat }}</p> <p>过滤器之filesizeformat--2:{{ file_size|filesizeformat }}</p> <p>过滤器之不使用date:{{ ctim }}</p> <p>过滤器之date:{{ ctim|date:'Y-m-d' }}</p> {#前闭后开区间#} <p>过滤器之slice:{{ ll|slice:'2:-1' }}</p> {#支持步长#} <p>过滤器之slice-字符串:{{ name|slice:'0:3:3' }}</p> {#三个起步,截出一部分#} <p>过滤器之truncatechars:{{ 'dafddfafgadfgaasdgadgfadaf'|truncatechars:5 }}</p> <p>过滤器之truncatewords:{{ '我 dfaf ga dfgaas 你 dgf adaf'|truncatewords:5 }}</p> <p>过滤器之不用safe:{{ h1 }}</p> <p>过滤器之用safe:{{ h1|safe }}</p> <p>过滤器之不用safe:{{ script }}</p> {#<p>过滤器之用safe:{{ script|safe }}</p>#} <p>过滤器之用add:{{ 12|add:'1' }}</p> <p>过滤器之用add:{{ 'egon'|add:'dsb' }}</p> {#safe跨站脚本攻击#} </body> </html>
urls文件
同上
其他方法(了解)
pass
五.模版之标签
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <hr> <h1>模板语言之标签</h1> {#{% for foo in ll %}#} {# {{ forloop }}#} {#<p>{{ forloop.first }}--->{{ forloop.counter0 }}--->{{ forloop.revcounter }}----->{{ foo }}</p>#} {#{% endfor %}#} {#{% for foo in ll %}#} {# {% for i in person_list %}#} {# 取出外层是第几次循环#} {# {{ forloop.parentloop.counter }}#} {# <p>{{ forloop.first }}--->{{ forloop.counter0 }}--->{{ forloop.revcounter }}----->{{ foo }}</p>#} {# {% endfor %}#} {#{% endfor %}#} {#**************循环的对象是空,才会走到empty,而不是对象里面的东西为空#} {#{% for foo in dic2 %}#} {# <p>{{ foo }}</p>#} {# {% empty %}#} {# 傻逼了#} {#{% endfor %}#} {#只循环字典的话,取到的是key值#} {#{% for foo in dic %}#} {#取到value的值#} {#{% for foo in dic.values %}#} {#取到key 和 value的值#} {#{% for k,foo in dic.items %}#} {# <p>{{ k }}----->{{ foo }}</p>#} {# {% empty %}#} {# 傻逼了#} {#{% endfor %}#} {#{% if user %}#} {# <a href="">退出</a>#} {# {% else %}#} {# <a href="">登录</a>#} {# <a href="">注册</a>#} {#{% endif %}#} {#for循环判断如果是第一次,打印第一次,其他打印正常值#} {% for foo in ll %} {% if forloop.first %} <p>第一次的我 </p> {% elif forloop.last %} <p>最后的我 </p> {% else %} <p>{{ foo }}</p> {% endif %} {% endfor %} <hr> {#with 相当于取别名,作用:变量太长,可以简化#} {% with name as ttt %} {{ ttt }} {{ name }} {{ user }} {% endwith %} ------ {% with dic.ll.2 as ttt %} {{ ttt }} {{ ttt }} {% endwith %} ************************for ,if,with 都要有结束******************
五.自定义标签和过滤器
html文件
<hr> <h1>自定义标签过滤器</h1> {% load mytag %} {#传多个参数的话:可以:'aaa:bb:cc',也可以:传列表#} <p>{{ 'lqz'|yyy:'nb' }}</p> <h4>使用自定义的标签</h4> <p>{% add_nb 'egon' %}</p> <p>{% add_3 'egon' 'is' 'dsb' %}</p> <hr> 过滤器,可以用在if判断中 {% if 'lqz'|yyy:'nb' %} <p>肯定是True</p> {% endif %} 标签不能用在if判断(报错) {#{% if add_nb 'egon' %}#} {# #} {#{% endif %}#} </body> </html>
详细步骤
--***标签不能用在if判断,过滤器,可以用在if判断 -自定义过滤器 -1 先app是不是已经在setting中注册 -2 在app下创建一个templatetags(****名字不能变***)的文件夹(模块) -3 在模块下创建一个py文件,名字随意:mytag.py -4 # 第一步,导入template from django.template import Library # 第二步,定义一个叫register的变量=template.Library() register = Library() -5 写一个函数,用@register.filter(name='yyy')装饰一下(可以指定别名) def str_add(str1, str2): #一定要有返回值 # 业务逻辑很复杂 return str1 + str2 -6 在模板里:(新定定义的标签,过滤器,都要重启程序) -{% load mytag %} -{{'lqz'|str_add:'nb'}} -自定义标签: -1-4:前4步,根过滤器的定义完全一样 -5 只是装饰器不一样 @register.simple_tag() def add_nb(value): return value+'nb' -6 在模板里:(多个参数,以空格区分) -{% load mytag %} -{% add_nb 'lqz'%}
六.模版导入和继承
6.1模版导入
模版导入-->写了一个好看的组件,可以复用, 1.写一个模板 2.在模板中:{% include '模板的名字'%} 模板导入的应用
template_test.html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="/static/utils/bootstrap-3.3.7-dist/css/bootstrap.css"> <title>Title</title> <style> .head { height: 60px; background: #1b6d85; } .content{ margin-top: 10px; } </style> </head> <body> <div class="head"></div> <div class="container-fluid content"> <div class="row"> <div class="col-md-3"> {% include 'left.html' %} </div> <div class="col-md-9"></div> </div> </div> </body> </html>
left.html文件
<div> <div class="panel panel-info"> <div class="panel-heading">重金求子</div> <div class="panel-body"> 重金求子:18888888 </div> </div> <div class="panel panel-danger"> <div class="panel-heading"> <h3 class="panel-title">老男孩教育</h3> </div> <div class="panel-body"> 老男孩教育 </div> </div> </div>
6.2母版的继承
1 写一个母版,留一个可扩展的区域(盒子),可以留多个盒子(留的越多,可扩展性越高) {%block 名字%} 可以写内容 {%endblock%} 2 在子模板中使用: {%block 名字%} 子模板的内容 {%endblock 名字%}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="/static/utils/bootstrap-3.3.7-dist/css/bootstrap.css"> <title>Title</title> <style> .head { height: 60px; background: #1b6d85; } .content{ margin-top: 10px; } </style> </head> <body> <div class="head"></div> <div class="container-fluid content"> <div class="row"> <div class="col-md-3"> {% include 'left.html' %} </div> <div class="col-md-9"> <div class="right_top" style="height: 70px;background: pink"> {% block content_top %} {% endblock %} </div> <div class="right_top" style="height: 70px;background: #3e8f3e"> </div> {% block content %} 我是母版的内容 {% endblock %} </div> </div> </div> </body> </html>
{#继承母版#} {% extends 'base.html' %} {% block content %} <p>这是9的区域</p> <p>这是9的区域</p> {{ block.super }} <p>这是9的区域</p> <p>这是9的区域</p> <p>这是9的区域</p> <p>这是9的区域</p> {# 继承自父类#} {{ block.super }} {% endblock content%} {% block content_top %} 我是模版一内容頭部 {% endblock content_top%}
{% extends 'base.html' %} {% block content %} <p>这是模板2的9的区域</p> <p>这是模板2的9的区域</p> <p>这是模板2的9的区域</p> <p>这是模板2的9的区域</p> <p>这是模板2的9的区域</p> <p>这是模板2的9的区域</p> {% endblock %}
七.静态文件相关
方便其动态的生成地址
1 写死静态文件:<link rel="stylesheet" href="/static/css/mycss.css"> 2 使用 static标签函数: -{%load static%} #static返回值,会拼上传参的路径 -{% static "传参"%} 3 使用get_static_prefix 标签 -{%load static%} #get_static_prefix返回值是:静态文件的地址,相当于/static/ -{% get_static_prefix %}css/mycss.css
htm文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> {# <link rel="stylesheet" href="/static/css/mycss.css">#} {% load static %} {# <link rel="stylesheet" href="{% static 'css/mycss.css' %}">#} <link rel="stylesheet" href="{% get_static_prefix %}css/mycss.css"> {# <link rel="stylesheet" href="/static12555/css/mycss.css">#} <title>Title</title> </head> <body> <h1>测试测试</h1> </body> </html>