Django学习 part2 模版

官方文档:

https://docs.djangoproject.com/en/1.11/ref/templates/builtins/#std:templatetag-for

常用语法:

模版中有两种特殊符号:

  1:{{ }}  通常用于变量 例如 render渲染的时候传递到html页面中的数据

  2:{%%} 通常使用于逻辑操作 例如 循环,条件判断等

变量

{{ 变量名 }}

变量名由字母,数字,下划线组成,英文句点.在模版语言中有特殊含义,用来获取对象的相应属性值.

views.py中的变量:

 1 from django.shortcuts import redirect,render,HttpResponse
 2 
 3 def index(request):
 4     a = [11, 22, 33]
 5     b = {"name": "qwe"}
 6 
 7     class Person(object):
 8         def __init__(self, name, age):
 9             self.name = name
10             self.age = age
11 
12         def dream(self):
13             return "{} is dream...".format(self.name)
14 
15     c = Person(name="c", age=34)
16     d = Person(name="b", age=34)
17     e = Person(name="e", age=34)
18     p_list = [c,d,e]
19     return render(request,'index.html',{'a':a,'b':b,'p_list':p_list})

在模版中:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <meta name="viewport" content="width=device-width, initial-scale=1">
 7 
 8 </head>
 9 <body>
10 {#获取a中的某一项,可以用英文句点加索引的方式获取#}
11 {{ a.1 }}
12 {#获取字典中的值,可以用英文句点加键的方式#}
13 {{ b.name }}
14 {#获取对象的属性#}
15 {{ p_list.0.name }}
16 {#调用不带参数的方法#}
17 {{ p_list.0.dream }}
18 
19 </body>
20 </html>

Filters

  这里的filter不是ORM操作中的filter方法,而是各种数据删选方法的统称

  语法:{{value|filter_name}}  注意:'|'左右没有空格

   default
{{ value:default: "nothing"}}
  length

  返回value的长度,例:value = [1,2,3,4],则查询后显示4

{{ value|length }}
  filesizeformat

  将一串数字转换为易读的文件尺寸(例如 '13 KB''4.1 MB''102 bytes', 等等)

{{ value|filesizeformat }}
  slice

  切片操作

{{value|slice:"2:-1"}}
  date

  时间格式化

{{ value|date:"Y-m-d H:i:s"}}
  safe

  当变量执行这个操作时,不会对这个变量进行自动转义.自动转义是Django的保护机制,会对HTML,JS等语法标签进行自动转义 例'<','>'等.防止有人利用漏洞向网站添加不安全的代码

{{ value|safe}}
  truncatechars

  字符串多余hi定的字符数量,将会被截断,截断后的部分将以ke可翻译的省略号结尾

{{ value|truncatechars:9}}

  自己定义的filter

  自定义过滤器只是带有一个或者两个参数的PYthon函数:

    变量的值 不一定是一个字符串

    参数的值 可以由一个默认值,或者完全省略

首先,定义自己的filter代码文件的位置:

app01/                        #app名
    __init__.py
    models.py    
    templatetags/             # 在app01下面新建一个package package
        __init__.py
        app01_filters.py      # 建一个存放自定义filter的文件
     

编写自定义的filter:

1 from django import template
2 register = template.Library()
3 # 貌似register是关键字不能修改
4 
5 
6 @register.filter(name='add_str')
7 def add_str(k,v):
8     return '{}{}'.format(k,v)

使用自定义filter:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <meta name="viewport" content="width=device-width, initial-scale=1">
 7 
 8 </head>
 9 <body>
10 {#导入自定义filter的文件#}
11 {% load my_filter %}
12 {#使用与内置filter一致#}
13 {{ a|add_str:'bbb' }}
14 
15 </body>
16 </html>

 

Tags

  for

循环:

{% for class in obj %}
        <tr>
        <td>{{ forloop.counter }}</td>
        <td>{{ class.id }}</td>
        <td>{{ class.name }}</td>
        <td>
            <button><a href="/class/delete_class?id={{ class.id }}">delete</a></button>
            <button><a href="/class/edit_class?id={{ class.id }}">edit</a></button>
        </td>
        </tr>
    {% endfor %}
Variable Description
forloop.counter 当前循环的索引值(从1开始)
forloop.counter0 当前循环的索引值(从0开始)
forloop.revcounter 当前循环的倒序索引值(从1开始)
forloop.revcounter0 当前循环的倒序索引值(从0开始)
forloop.first 当前循环是不是第一次循环(布尔值)
forloop.last 当前循环是不是最后一次循环(布尔值)
forloop.parentloop 本层循环的外层循环
  for ...empty

常用在取值时遇到空,给予一个友好反馈

<ul>
{% for user in user_list %}
    <li>{{ user.name }}</li>
{% empty %}
    <li>空空如也</li>
{% endfor %}
</ul>
  if,elif 和 else
{% if user_list %}
  用户人数:{{ user_list|length }}
{% elif black_list %}
  黑名单数:{{ black_list|length }}
{% else %}
  没有用户
{% endif %}

if语句支持 and 、or、==、>、<、!=、<=、>=、in、not in、is、is not判断。

  with

用于定义一个中间变量

{% with total=business.employees.count %}
    {{ total }} employee{{ total|pluralize }}
{% endwith %}

 csrf_tocken

这个标签用于跨站请求伪造保护。

在页面的form表单里面写上{% csrf_token %}

 

母板

 1 {% load static %}
 2 
 3 <!DOCTYPE html>
 4 <html lang="en">
 5 <head>
 6     <meta charset="UTF-8">
 7     <title>{% block title %}
 8     {% endblock %}</title>
 9     <meta name="viewport" content="width=device-width, initial-scale=1">
10     <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}">
11 
12     {% block css %}{% endblock %}
13 
14 
15 </head>
16 <body>
17 {#导航#}
18 {% block nav %}
19 <nav class="navbar navbar-default navbar-static-top">
20     <div class="container-fluid">
21         <!-- Brand and toggle get grouped for better mobile display -->
22         <div class="navbar-header">
23             <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
24                     data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
25                 <span class="sr-only">Toggle navigation</span>
26                 <span class="icon-bar"></span>
27                 <span class="icon-bar"></span>
28                 <span class="icon-bar"></span>
29             </button>
30             <a class="navbar-brand" href="{% url 'index' %}">主页</a>
31         </div>
32 
33         <!-- Collect the nav links, forms, and other content for toggling -->
34         <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
35             <ul class="nav navbar-nav">
36                 <li ><a href="/cla/">班级管理 <span class="sr-only">(current)</span></a></li>
37                 <li><a href="/stu/">学生管理</a></li>
38                 <li><a href="/tea/">教师管理</a></li>
39             </ul>
40             <form class="navbar-form navbar-left pull-right">
41                 <div class="form-group">
42                     <input type="text" class="form-control" placeholder="Search">
43                 </div>
44                 <button type="submit" class="btn btn-default">Submit</button>
45             </form>
46 
47         </div><!-- /.navbar-collapse -->
48     </div><!-- /.container-fluid -->
49 </nav>
50 {% endblock %}
51 {#导航结束#}
52 {% block body %}
53 {% endblock %}
54 
55 <script src="{% static 'js/jquery-3.2.1.min.js' %}"></script>
56 <script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>
57 {% block js %}{% endblock %}
58 </body>
59 </html>

通常我们会在母板中留下专门专门写css,js以及body内容的块.

继承母板

子页面加载母板内容,要在页面最上方执行该语句

{% extends '母板名.html' %}

母板中给子页面预留的位置即为块,子页面的内容写在endblock之前

{% block body %}
{% endblock %}

组建

有些常用的页面内容,如导航条尾页信息等,可以单独存在文件中,在需要的时候 按语法导入即可.

eg:

{% include 'navbar.html' %}

静态文件相关

需要在页面上方加载static去自动获取static的名字

{% load static %}

使用时:

<link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}">

也可以使用:

get_static_prefix

{% load static %}
<img src="{% get_static_prefix %}images/hi.jpg" alt="Hi!" />

自定义simpletag

与自定义filter类似,但是它接收更灵活的参数.

定义注册simpletag

@register.simple_tag(name="plus")
def plus(a, b, c):
    return "{} + {} + {}".format(a, b, c)

使用自定义simpletag

{% load app01_demo %}

{# simple tag #}
{% plus "1" "2" "abc" %}

inclusion_tag

多用于返回html代码片段

示例:

templatetags/my_inclusion.py

from django import template

register = template.Library()


@register.inclusion_tag('result.html')
def show_results(n):
    n = 1 if n < 1 else int(n)
    data = ["第{}项".format(i) for i in range(1, n+1)]
    return {"data": data}

templates/snippets/result.html

<ul>
  {% for choice in data %}
    <li>{{ choice }}</li>
  {% endfor %}
</ul>

templates/index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="x-ua-compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>inclusion_tag test</title>
</head>
<body>

{% load inclusion_tag_test %}

{% show_results 10 %}
</body>
</html>

 

posted @ 2018-03-29 18:33  darkfitch  阅读(106)  评论(0)    收藏  举报