55.django模板层(templates)

1.简介

  通过使用模板,就可以在URL中直接调用HTML,它还是松耦合的,灵活性强,而且更容易维护

  而且可以将变量通过一定的方式嵌入到HTML中,最终渲染到页面,总的来说基于模板完成了数据与用户之间的交互

1.1模板HTML中的变量

  用两个大括号括起来的文字(例如  {{ person_name }} )称为  变量 (variable)

url部分

urlpatterns = [
    path("third/",views.indexs)
]

views部分

import datetime
def indexs(request):
    hel = "hello"
    lis_year = [18, 22, 32]  # 列表
    dic = {"name": "luffy", "age": 18}  # 字典
    date = datetime.datetime.now() # 日期对象

    class Person(object):
        def __init__(self, name):
            self.name = name

    person_1 = Person("zoro")  # 自定义类对象
    person_2 = Person("sanzhi")
    person_3 = Person("robin")
    person = [person_1, person_2, person_3]

    return render(request, "index.html",
        {"hel":hel,"l": lis_year, "dic": dic, "ship_data": date, "person_list": person})

templates部分(名称index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h4>{{ hel }},</h4>
    <h4>my name is {{ dic.name.upper }}.</h4>  {# 句点符引用对象的方法 #}
    <h4>I'm  {{ l.0 }}'s old.</h4>   {# 视图对象索引0的值 #}
    <h4>and my born year is {{ ship_data|date:"y-m-d" }}.</h4>
    {% for name in person_list %}   {# 遍历每一个元素 #}
    <h4> my partner is {{ name.name }}</h4>  {# 类对象列表 #}
    {% endfor %}    {# 必须要包含结束标志 #}
</body>
</html>

# 注意这里调用字符串的方法时并* 没有* 使用圆括号 而且也无法给该方法传递参数;你只能调用不需参数的方法

最终效果

1.2模板语法

 1.2.1 过滤器模板

default

default		# 如果一个变量是false或为空,使用给定默认值,否则使用变量的值
{{value|deafult:"666"}}  

 length

length 		# 返回值的长度,如 value 是 ['a', 'b', 'c', 'd'],那么输出是 4
{{ value|length }}

filesizeformat

filesizeformat	# 将值格式化为一个可读的文件尺寸,如 value 是 123456789,输出将会是 117.7 MB
{{ value|filesizeformat }}

 date

date 如value=datetime.datetime.now()	
{{ value|date:"Y-m-d" }} 

 slice 

slice 	# 切片
{{ value|slice:"2:-1" }}

 truncatechars

truncatechars	# 截断,如果字符串字符多于指定的字符数量,那么会被截断。截断的字符串将以可翻译的省略号序列(“...”)结尾	参数:要截断的字符数
{{ value|truncatechars:9 }}
<p>截断字符:{{ content|truncatechars:20 }}</p>
<p>截断单词:{{ content|truncatewords:4 }}</p>

 safe

safe 	# django会对模板中的语法自动转移,但是出于安全考虑,对于一些具有带链接跳转的功能标签则不会进行转义(如a标签)
{{value|safe}}

 这里给演示一下safe的用法

url部分

from app01 import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('views/',views.views)

views部分

  这里一开始我以为value这块是写在模板中,但是不是的,他属于视图部分,只是在模板这里添加了{{ value|safe}}这一步

def views(request):
    lis = ['das','two','three','four']
    value = "<a href='http://www.baidu.com'>click</a>"
    
    # 这里使用locals直接将上面的参数封装成了字典形式
    return render(request,'test.html',locals())
    # return render(request,'test.html',{"lis":lis,"value":value})

templates部分(test.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h3>字典:{{ lis|slice:'1:-1' }}</h3>
    {{ value|safe }}
</body>
</html>

 标签模板

for标签

遍历每一个元素
{% for person in person_list %}
    <p>{{ person.name }}</p>
{% endfor %}

 # 可以利用{% for obj in list reversed %}反向完成循环 

遍历一个字典

{% for key,val in dic.items %}
    <p>{{ key }}:{{ val }}</p>
{% endfor %}

 # 这里循环序号可以通过{{forloop}}显示 

forloop.counter            The current iteration of the loop (1-indexed)
forloop.counter0           The current iteration of the loop (0-indexed)
forloop.revcounter         The number of iterations from the end of the loop (1-indexed)
forloop.revcounter0        The number of iterations from the end of the loop (0-indexed)
forloop.first              True if this is the first time through the loop
forloop.last               True if this is the last time through the loop

for...empty

# 在给出的组是空的或者没有被找到时,可以有所操作。
{% for person in person_list %}
    <p>{{ person.name }}</p>

{% empty %}
    <p>sorry,no person here</p>
{% endfor %}  

 if标签

# 对一个变量进行求值,如果它的值是“True”(存在、不为空、且不是boolean类型的false值),对应的内容块会输出
{% if num > 100 or num < 0 %}
    <p>无效</p>
{% elif num > 80 and num < 100 %}
    <p>优秀</p>
{% else %}
    <p>凑合</p>
{% endif %}  

 with

# 用一个简单地名字缓存一个复杂的变量,当你需要使用一个“昂贵的”方法(比如访问数据库)很多次的时候是非常有用
{% with total=business.employees.count %}
    {{ total }} employee{{ total|pluralize }}
{% endwith %}

csrf_token 

csrf_token 	# 该标签用于跨站请求伪造保护

 相关例子示例:

views部分

def temps(request):
    lis = [10,20,30,50]
    dic = {"name":"luffy","age":18}
    lis =  ['one','two','three','four']
    num = 80
    login_user = 66
    return render(request,'test.html',locals())

templates部分(test.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {% for num in lis %}
        <h3> {{ num|add:100 }}</h3>   {# 这里可以加减,带负号即可,没有乘除 #}
    {% endfor %}


    {% for k,v in dic.items %}      {# 注意这里是dic.items #}
        <h3>{{ k }}:{{ v }}</h3>
    {% endfor %}


    {% for temp in lis %}
        <h3>{{ forloop.counter }}{{ temp }}</h3>   {# 从1开始排 #}
    {% endfor %}


    {% if num >= 80 and num < 100 %}  {# 注意空格,不然会飘红 #}
        <h3>优秀</h3>
    {% elif num >= 60 and num < 80 %}
        <h3>良好</h3>
    {% elif num < 60 %}
        <h3>不及格</h3>
    {% else %}
        <h2>出错啦</h2>
    {% endif %}


    <hr>
    {% if login_user %}
        <p>{{ login_user.name }}</p>
        <a href="">注销</a>
        <a href="">修改密码</a>
    {% else %}
        <a href="">登陆</a>
        <a href="">注册</a>
    {% endif %}
    <hr>


    <form action="" method="post">
        {% csrf_token %}    {# 用于伪造保护,否则django会拒收报forbidden #}
    <input type="submit">
    </form>
</body>
</html>

效果

 

猜你喜欢

转载自www.cnblogs.com/LearningOnline/p/9221956.html
今日推荐