Python-Django 模板层

1 模版简介

DTL:django模板语言
核心:
变量 {{ }}
标签 {% %}css

2 模版语法之变量

-变量渲染:{{变量}}
-变量深度查询:{{变量.索引/key值/方法}}html

 

<h2>当前时间戳</h2>
@@time@@
{{ ctime }}
<h1>变量</h1>
<p>{{ age }}</p>
<p>{{ name }}</p>
<p>{{ dic }}</p>
<p>{{ li }}</p>
<h2>取出字典的名字</h2>
<p>{{ dic.name }}</p>
<h2>取出列表中的某个值</h2>
<p>{{ li.0 }}</p>
<h2>变量之对象</h2>
<p>{{ lqz }}</p>
<p>{{ lqz.test1 }}</p>
<h2>类调用方法不行,智能用对象</h2>
<p>{{ Test.test2 }}</p>
<p>{{ lqz.test2 }}</p>
def test(request):
    # 显示时间戳
    # with open('templates/test01.html','r') as f:
    #     data=f.read()
    # data=data.replace('@@time@@',str(time.time()))
    # return HttpResponse(data)
    # ctime=str(time.time())
    # return render(request, 'test01.html', {'ctime': ctime})
    # 变量
    age=17
    name='dhhfg'
    dic={'name':'红楼','pub_date':'2018-12-30','price':888}
    li=['dgfgf',18]
    li2=[]
    # locals()把全部局部变量传到模板中
    class Test():
        def __init__(self, name, pwd):
            self.name = name
            self.pwd = pwd
        def test1(self):
            return self.name
        def __str__(self):
            return self.pwd
        @classmethod
        def test2(cls):
            return 'clsss'

    lqz = Test('lqz', '123')
    # print(lqz)
    # print(lqz.test1())

    file_size=10240000
    bol=[]
    import _datetime
    today=_datetime.datetime.now()
    h1='hello world abc'
    href='<a href="http://www.baidu.com">baidu</a>'
    from django.utils.safestring import mark_safe
    href2=mark_safe(href)
    return render(request,'test01.html',locals())

  

3 模版之过滤器

变量之过滤器(是个函数)
-语法:(后面只能传一个参数)
{{变量名|过滤器的名字:参数}}
-内置过滤器:
<p>{{ age|add:3 }}</p>
<p>{{ name|length }}</p>
<p>{{ bol|default:'123' }}</p>
<p>{{ ll2|default:'我是空的' }}</p>
<p>{{ file_size|filesizeformat }}</p>
<p>{{ ctime }}</p>
<p>{{ ctime|date:'Y年m月' }}</p>
<p>{{ name|slice:'2:4' }}</p>
<p>{{ name|truncatechars:6 }}</p>
<p>{{ name2|truncatewords:2}}</p>
<p>{{ href|safe }}</p>python

 

<h1>过滤器</h1>
<p>age+100</p>
<p>{{ age|add:100 }}</p>
<p>name lenght</p>
<p>{{ name|length }}</p>
<p>bol default</p>
<p>{{ bol|default:'123' }}</p>
<h2>filesize </h2>
<p>{{ file_size|filesizeformat }}</p>
<h2>date</h2>
<p>{{ today|date:'Y年m月d日' }}</p>
<h2>slice</h2>
<p>{{ h1|slice:':-1' }}</p>
<p>{{ h1|slice:'0:2' }}</p>
<p>{{ h1|slice:'-5:-1' }}</p>
<h2>truncatehars</h2>
<p>{{ h1|truncatechars:6 }}</p>
<h2>truncatewords</h2>
<p>{{ h1|truncatewords:2 }}</p>
<h2>href</h2>
<p>{{ href|safe }}</p>
#django已经避免xss攻击,但慎用safe,确认内容是否安全,注意xss攻击(跨站脚本攻击),如<script>alert(123)</script>
<p>{{ href2 }}</p>
或者from django.utils.safestring import mark_safe
href2=mark_safe(href)

4 模版之标签

-语法:{% %}
-foo是一个可迭代对象
{% for a in foo %}web

{% endfor %}
-forloop:counter,couter0,revcounter,revcouter0,first,last,parentloop:父循环的forloop对象
-for--empty的使用
{% for foo in ll2 %}
{{ foo }}
{% empty %}
没有值啊
{% endfor %}
-if判断
{% if ll2 %}
ll2 有值
{% elif ll %}
ll有值
{% else %}
ll2 没有值
{% endif %}
-with重命名
{% with dic.hobby.1 as a %}
{#{% with a=dic.hobby.1 %}#}
{{ a }}
<p>aaaa</p>
{{ a }}django

{% endwith %}flask

 

<h1>模板之标签</h1>
<h2>for</h2>
{% for foo in li %}
<p>{{ foo }}</p>
{% endfor %}
<h2>li2------</h2>
{% for foo in li2 %}
<p>{{ foo }}</p>
{% empty %}
<p>no,data</p>
{% endfor %}
<h2>if</h2>
{% if li %}
data
{% elif age > 10 %}
age>10
{% else %}
age<10
{% endif %}
<h2>with</h2>
{#{% with li.1 as a %}#}
{% with a=li.0 %}
{{ a }}
{% endwith %}

5 自定义过滤器

1 确认app是否在settings中注册
2 在app下建立templatetags的模块(名字固定)
3 在模块下建立py文件(名字随意)--->在模板中{% load py文件名字%}
4 在py文件中写过滤器
from django.template import Library
register = Library()
#指定了name以后,模板上使用的时候,直接用name调用,若是没指定name,就用函数的名字
# 过滤器最多有两个参数
@register.filter(name='myadd')
def my_add(a,b):
print(a+b)
return a+b
5 模板中使用
-1 {% load py文件名字%}
-2 {{ 变量|myadd:1}}bootstrap

 

from django.template import Library
from app01.models import *

register = Library()
#指定了name以后,模板上使用的时候,直接用name调用,若是没指定name,就用函数的名字
# 过滤器最多有两个参数
@register.filter(name='myadd')
def my_add(a,b):
print(a+b)
return a+b

{% load my_tag %}
{{ age|myadd:4 }}
{% if age|myadd:4 > 20 %}
大于20
{% endif %}
# -写一个过滤器:
# -实现过滤敏感词汇
# 操--->和谐
# 你麻痹--->民主
# -替换的字符,是能够配置的
def data(request):
if request.method=='GET':
inputall = models.Input.objects.all()
return render(request,'test_sen_input.html',{'content':inputall})
else:
con = request.POST.get('content')
print(con)
ret = Input.objects.create(data=con)
# return HttpResponse('添加成功')
return redirect('/data/')


@register.filter(name='senword')
def sen_word(word):
sen_word=Sen.objects.filter(sen=word)
if sen_word:
return sen_word[0].cha
return word

{% for i in content %}
{% load my_tag %}
<p>{{ i.data|senword }}</p>
{% endfor %}


6 自定义标签

1 确认app是否在settings中注册
2 在app下建立templatetags的模块(名字固定)
3 在模块下建立py文件(名字随意)--->在模板中{% load py文件名字%}
4 在py文件中写过滤器
from django.template import Library
register = Library()
#指定了name以后,模板上使用的时候,直接用name调用,若是没指定name,就用函数的名字
# 过滤器最多有两个参数
@register.simple_tag(name='mytag')
def my_tag(a,b,c):
return a+b+c
5 模板中使用
-1 {% load py文件名字%}
-2 {% mytag 参数1 参数2 参数3%}浏览器

 

# 自定义一个标签
# 标签能够传多个参数
@register.simple_tag(name='mytag')
def my_tag(a,b,c):
return a+b+c

{#标签不能跟在if判断后面#}
{#{% if mytag 1 2 3 > 30 %}#}
{# #}
{#{% endif %}#}
{% mytag 1 2 3 %}

7 标签和过滤器的区别:

1 标签能够传多个参数,过滤器最多只能传2个
2 使用过滤器{{ }} 标签使用:{% %}
3 ****重点:过滤器能够放在if判断后,标签不能放在if判断后安全

 

wsgiref,uwsgi,---都遵循wsgi协议

-遵循一个协议wsgi(Web Server Gateway Interface web服务网关接口)服务器

web应用: 

-S包括两部分:web服务器+application
-目前阶段django项目用的web服务器是:wsgiref(并发性很差)+application(django)
-上线会用uwsgi+application
-web服务器(本质是socket)都实现了wsgi协议
-wsgi:web服务网关接口,是一个协议

 

 


模板的导入和继承

-如何引入静态文件(static目录的配置)
-模板的导入:
1 写一个好看的模板
2 在想用的地方:
{% include '好看模板的名字.html' %}
-模板的继承
-写一个母版,base.html(留一些block(盒子)),留的盒子越多,可扩展性就越高
{% block top %}

{% endblock %}
-使用:
-在一个新的html中
-{%extend 'base.html'%}
-扩写留的对应的盒子
{% block top %}
扩写的内容
{% endblock %}
-注意:
1 扩写的时候,盒子的位置无所谓,只要名字对应正确,就会正确填充
2 盒子能够不扩写,不写就是原来的样子
3 若是要显示母版盒子中原来的东西,须要
{{block.super}}----写在哪,原来的内容就放在哪

静态文件相关

1 直接写死的:<link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
2 用static标签:
{% load static %}
<link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.css' %}">
3 用get_static_prefix:
{% load static %}
<link rel="stylesheet" href="{% 用get_static_prefix %}bootstrap-3.3.7-dist/css/bootstrap.css">

inclusion_tag:返回html片断

1 前面几步跟标签和过滤器同样
2 装饰器:@register.inclusion_tag('inclusiontag.html',name='lqz'),第一个参数是要操做的模板
3 返回一个字典,字典中的值,能够在inclusiontag中使用
4 使用:
{%load 你写的那个py文件%}
{% 函数名字 参数 参数 %}

from django.template import Library
from app01.models import *

register=Library()

@register.inclusion_tag('inclusion_tag.html',name='books')
def mytag(num):
books = Book.objects.all()[:int(num)]
return {'books':books}

{% load my_tag %}
{% books num %}

def select(request):
num=0
if request.method=='POST':
num=request.POST.get('input')
return render(request, 'select.html',{'num':num})


TTL:

 

 

1 模板语言之变量:
-{{ }} 至关于执行了print
-深度查询 . 若是是方法,不能加括号,不能传参数
2 过滤器
{{ 变量|过滤器的名字:'参数' }}
-add
-default
-safe:(慎重,注意xss攻击)
-在视图层处理标签字符串:href2=mark_safe(href)
-length
-date
...
3 xss攻击
-跨站脚本攻击
4 标签:
-for :
{% for i in 可迭代对象 %}
{{forloop}}
{%empty%}
可迭代对象为空,会执行这里
{%endfor%}
-if : > < and in or ...
{%if 条件%}
{%if 条件2}
{%for %}

{%endfor%}
{%endif%}

{%elif 条件%}

{%else%}

{%endif%}

-with:命别名

5 自定义标签,过滤器
1 app是否注册
2 templatetags模块:名字必定不能错
3 建立py文件(名字随意)
4 from django.template import Library
5 register=Library()
6 写过滤器:
@register.filter(name='别名')
def myfilter(a,b):
逻辑处理
return XX
7 写个标签:
@register.simple_tag(name='别名')
def myfilter(a,b,c):
逻辑处理
return XX
8 使用过滤器
{%load mytag %}
{{变量|过滤器名:'参数'}}
9 使用标签
{%load mytag %}
{% 标签名 参数1 参数2%}
10区别:
1 过滤器最多两个参数,标签能够多个
2 使用的时候,{{过滤器}},{% 标签%}
3 **** 过滤器能够放在if判断中,for循环中
6 模板语言注释:
{#要注释的内容#}
-这种注释,在浏览器中是看不到的

-http请求的本质: -socket -web应用 -server + application -测试阶段:wsgiref -项目上线:uwsgi a:socket b:路由映射关系 c:模板语言的渲染 django: a:用别人的 b:本身写的 c:本身写的 flask: a:别人的 b:本身写的 c:用了别人的 tornado:a:本身写的 b:本身写的 c:本身写的 -模板导入: -写了一个很好看组件(模板) {% include '名字'%} -模板的继承 -写一个母版,留好的盒子 {%block 名字%} 写东西 {% endblock%} -{%extends '母版的名字'%} - {%block 名字%} 写东西 {{block.super}} {% endblock%} -静态文件相关 -在setting中: -STATICFILES_DIRS=[文件夹的路径,] -在模板中使用: 1 路径写死 2 动态的生成全路径: {% load static %} {%static '静态文件路径'%} 3 只获取static的路径 {% load static %} {% get_static_prefix %} -inclusion_tag -反回一个html片断

相关文章
相关标签/搜索