欢迎来到战五渣的博客

人生三重境界:昨夜西风凋碧树,独上高楼,望尽天涯路。 衣带渐宽终不悔,为伊消得人憔悴。 众里寻他千百度,蓦然回首,那人却在灯火阑珊处。

053.Python前端Django框架模板层

模板层

一 模板语法之变量

在 Django 模板中遍历复杂数据结构的关键是句点字符, 语法: 

{{ var_name }}

[root@node10 mysite]# cat app01/urls.py

from django.urls import path,re_path
from . import views
urlpatterns = [
    path("test/",views.test1,name="test1"),
    path("temp_test/",views.temp_test),
]

[root@node10 mysite]# vim app01/views.py

#模板相关
def temp_test(request):
        name = "ning"
        return render(request,"temp_test.html",{"name":name})     #这里定义的必须和html调用的名称一致

[root@node10 mysite]# vim templates/temp_test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</script>
</head>
<body>
        <h3>{{name}}</h3>
<script>
</script>
</body>
</html>

访问http://192.168.132.140:8888/app01/temp_test/

 其他方法

[root@node10 mysite]# vim app01/views.py

#模板相关
def temp_test(request):
        name = "ning"
        list1 = ["john","dachun","joy"]
        dict1 = {"name":"joy","Age":18}
        class A:
                def __init__(self,name,age):
                        self.name = name
                        self.age = age
                def test(self):
                        return "333666"
        a1 = A("john",18)
        a2 = A("dachun",20)
        a3 = A("joy",22)
        return render(request,"temp_test.html",{"name":name,
                                                "list1":list1,
                                                "dict1":dict1,
                                                "a1":a1,
                                                "a2":a2,
                                                "a3":a3
                                                                })

[root@node10 mysite]# vim templates/temp_test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</script>
</head>
<body>
        <h3>{{name}}</h3>
        <p>{{list1}}</p>
        <p>{{list1.1}}</p>
        <p>{{dict1}}</p>
        <p>{{dict1.name}}</p>
        <p>{{dict1.Age}}</p>
        <p>{{a1}}</p>
        <p>{{a1.name}}</p>
        <p>{{a1.name.upper}}</p>
        <p>{{a2.test}}</p>

<script>
</script>
</body>
</html>

访问http://192.168.132.140:8888/app01/temp_test/

[root@node10 mysite]# vim app01/views.py

def temp_test(request):
    import datetime
    s="hello"
    l=[111,222,333]    # 列表
    dic={"name":"yuan","age":18}  # 字典
    date = datetime.date(1993, 5, 2)   # 日期对象

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

    person_yuan=Person("yuan")  # 自定义类对象
    person_egon=Person("egon")
    person_alex=Person("alex")

    person_list=[person_yuan,person_egon,person_alex]


    return render(request,"temp_test.html",{"l":l,"dic":dic,"date":date,"person_list":person_list})

[root@node10 mysite]# vim templates/temp_test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</script>
</head>
<body>
        <h4>{{s}}</h4>
        <h4>列表:{{ l.0 }}</h4>
        <h4>列表:{{ l.2 }}</h4>
        <h4>字典:{{ dic.name }}</h4>
        <h4>日期:{{ date.year }}</h4>
        <h4>类对象列表:{{ person_list.0.name }}</h4>
<script>
</script>
</body>
</html>

访问http://192.168.132.140:8888/app01/temp_test/

二 模板语法之过滤器

过滤器最多只有两个参数

语法:

{{obj|filter__name:param}}
如果一个变量是false或者为空,使用给定的默认值。否则,使用变量的值。例如:

[root@node10 mysite]# vim app01/views.py

def temp_test(request):
        name = ""
        list1 = ["john","dachun","joy"]
        dict1 = {"name":"joy","Age":18}
        class A:
                def __init__(self,name,age):
                        self.name = name
                        self.age = age
                def test(self):
                        return "333666"
        a1 = A("john",18)
        a2 = A("dachun",20)
        a3 = A("joy",22)

        return render(request,"temp_test.html",{"name":name,
                                                "list1":list1,
                                                "dict1":dict1,
                                                "a1":a1,
                                                "a2":a2,
                                                "a3":a3
                                                                })

[root@node10 mysite]# vim templates/temp_test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</script>
</head>
<body>
        <h3>{{name|default:"nobody"}}</h3>
        <p>{{list1}}</p>
        <p>{{list1.1}}</p>
        <p>{{dict1}}</p>
        <p>{{dict1.name}}</p>
        <p>{{dict1.Age}}</p>
        <p>{{a1}}</p>
        <p>{{a1.name}}</p>
        <p>{{a1.name.upper}}</p>
        <p>{{a2.test}}</p>
<script>
</script>
</body>
</html>

访问http://192.168.132.140:8888/app01/temp_test/

2.1 length

返回值的长度。它对字符串和列表都起作用。例如:

{{ value|length }}

如果 value 是 ['a', 'b', 'c', 'd'],那么输出是 4。

[root@node10 mysite]# vim app01/views.py

def temp_test(request):
        name = "darren"
        list1 = ["john","dachun","joy"]
        dict1 = {"name":"joy","Age":18}
        class A:
                def __init__(self,name,age):
                        self.name = name
                        self.age = age
                def test(self):
                        return "333666"
        a1 = A("john",18)
        a2 = A("dachun",20)
        a3 = A("joy",22)

        return render(request,"temp_test.html",{"name":name,
                                                "list1":list1,
                                                "dict1":dict1,
                                                "a1":a1,
                                                "a2":a2,
                                                "a3":a3
                                                                })

[root@node10 mysite]# vim templates/temp_test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</script>
</head>
<body>
        <h3>{{name|default:"nobody"}}</h3>
        <h3>{{name|length}}</h3>
        <p>{{list1}}</p>
        <p>{{list1.1}}</p>
        <p>{{dict1}}</p>
        <p>{{dict1.name}}</p>
        <p>{{dict1.Age}}</p>
        <p>{{a1}}</p>
        <p>{{a1.name}}</p>
        <p>{{a1.name.upper}}</p>
        <p>{{a2.test}}</p>
<script>
</script>
</body>
</html>

访问http://192.168.132.140:8888/app01/temp_test/

2.2 filesizeformat

将值格式化为一个 “人类可读的” 文件尺寸 (例如 '13 KB', '4.1 MB', '102 bytes', 等等)。例如:

{{ value|filesizeformat }}

如果 value 是 123456789,输出将会是 117.7 MB。

[root@node10 mysite]# vim templates/temp_test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</script>
</head>
<body>
        <h3>{{name|default:"nobody"}}</h3>
        <h3>{{num|filesizeformat}}</h3>
        <p>{{list1}}</p>
        <p>{{list1.1}}</p>
        <p>{{dict1}}</p>
        <p>{{dict1.name}}</p>
        <p>{{dict1.Age}}</p>
        <p>{{a1}}</p>
        <p>{{a1.name}}</p>
        <p>{{a1.name.upper}}</p>
        <p>{{a2.test}}</p>
<script>
</script>
</body>
</html>

[root@node10 mysite]# vim app01/views.py

#模板相关
def temp_test(request):
        name = "darren"
        num = 12344656787778
        list1 = ["john","dachun","joy"]
        dict1 = {"name":"joy","Age":18}
        class A:
                def __init__(self,name,age):
                        self.name = name
                        self.age = age
                def test(self):
                        return "333666"
        a1 = A("john",18)
        a2 = A("dachun",20)
        a3 = A("joy",22)

        return render(request,"temp_test.html",{"name":name,
                                                "list1":list1,
                                                "dict1":dict1,
                                                "a1":a1,
                                                "a2":a2,
                                                "num":num
                                                                })

访问http://192.168.132.140:8888/app01/temp_test/

2.3 date

如果 value=datetime.datetime.now()

{{ value|date:"Y-m-d" }} 

[root@node10 mysite]# vim templates/temp_test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</script>
</head>
<body>
        <h3>{{name|default:"nobody"}}</h3>
        <h3>{{num|filesizeformat}}</h3>
      <p>{{now_time|date:"Y-m-d"}}</p> <p>{{list1}}</p> <p>{{list1.1}}</p> <p>{{dict1}}</p> <p>{{dict1.name}}</p> <p>{{dict1.Age}}</p> <p>{{a1}}</p> <p>{{a1.name}}</p> <p>{{a1.name.upper}}</p> <p>{{a2.test}}</p> <script> </script> </body> </html>

[root@node10 mysite]# vim app01/views.py

#模板相关
import datetime def temp_test(request): name = "darren" num = 12344656787778
     now_time=datetime.datetime.now() list1 = ["john","dachun","joy"] dict1 = {"name":"joy","Age":18} class A: def __init__(self,name,age): self.name = name self.age = age def test(self): return "333666" a1 = A("john",18) a2 = A("dachun",20) a3 = A("joy",22) return render(request,"temp_test.html",{"name":name, "list1":list1, "dict1":dict1, "a1":a1, "a2":a2, "num":num,
                             "now_time":now_time })

访问http://192.168.132.140:8888/app01/temp_test/

2.4 truncatechars

如果字符串字符多于指定的字符数量,那么会被截断。截断的字符串将以可翻译的省略号序列(“...”)结尾。

参数:要截断的字符数,例如:

{{ value|truncatechars:10 }}

[root@node10 mysite]# vim templates/temp_test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</script>
</head>
<body>
        <h3>{{name|default:"nobody"}}</h3>
        <h3>{{num|filesizeformat}}</h3>
     <p>{{now_time|date:"Y-m-d"}}</p>
     <p>{{str1|truncatechars:10}}</p>
     <p>{{list1}}</p> <p>{{list1.1}}</p> <p>{{dict1}}</p> <p>{{dict1.name}}</p> <p>{{dict1.Age}}</p> <p>{{a1}}</p> <p>{{a1.name}}</p> <p>{{a1.name.upper}}</p> <p>{{a2.test}}</p> <script> </script> </body> </html>

[root@node10 mysite]# vim app01/views.py

#模板相关
import datetime def temp_test(request): name = "darren" num = 12344656787778
     now_time=datetime.datetime.now()
     str1="There’s a special providence in the fall of a sparrow" list1 = ["john","dachun","joy"] dict1 = {"name":"joy","Age":18} class A: def __init__(self,name,age): self.name = name self.age = age def test(self): return "333666" a1 = A("john",18) a2 = A("dachun",20) a3 = A("joy",22) return render(request,"temp_test.html",{"name":name, "list1":list1, "dict1":dict1, "a1":a1, "a2":a2, "num":num,
                             "now_time":now_time,
                             "str1":str1 })

访问http://192.168.132.140:8888/app01/temp_test/

2.5 safe

Django的模板中会对HTML标签和JS等语法标签进行自动转义,原因显而易见,这样是为了安全。但是有的时候我们可能不希望这些HTML元素被转义,比如我们做一个内容管理系统,后台添加的文章中是经过修饰的,这些修饰可能是通过一个类似于FCKeditor编辑加注了HTML修饰符的文本,如果自动转义的话显示的就是保护HTML标签的源文件。为了在Django中关闭HTML的自动转义有两种方式,如果是一个单独的变量我们可以通过过滤器“|safe”的方式告诉Django这段代码是安全的不必转义。比如:

[root@node10 mysite]# vim app01/views.py

#模板相关
import datetime
def temp_test(request):
        now_time=datetime.datetime.now()
        name = "darren"
        num = 12344656787778
        str1="There’s a special providence in the fall of a sparrow"
        str_a="<a href=\"www.baidu.com\">点击</a>"
        list1 = ["john","dachun","joy"]
        dict1 = {"name":"joy","Age":18}
        class A:
                def __init__(self,name,age):
                        self.name = name
                        self.age = age
                def test(self):
                        return "333666"
        a1 = A("john",18)
        a2 = A("dachun",20)
        a3 = A("joy",22)

        return render(request,"temp_test.html",{"name":name,
                                                "list1":list1,
                                                "dict1":dict1,
                                                "a1":a1,
                                                "a2":a2,
                                                "num":num,
                                                "now_time":now_time,
                                                "str1":str1,
                                                "str_a":str_a
                                                                })

[root@node10 mysite]# vim templates/temp_test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</script>
</head>
<body>
        <h3>{{name|default:"nobody"}}</h3>
        <h3>{{num|filesizeformat}}</h3>
        <p>{{now_time|date:"Y-m-d"}}</p>
        <p>{{str1|truncatechars:10}}</p>
        <p>{{str_a}}</p>
        <p>{{str_a|safe}}</p>
        <p>{{list1}}</p>
        <p>{{list1.1}}</p>
        <p>{{dict1}}</p>
        <p>{{dict1.name}}</p>
        <p>{{dict1.Age}}</p>
        <p>{{a1}}</p>
        <p>{{a1.name}}</p>
        <p>{{a1.name.upper}}</p>
        <p>{{a2.test}}</p>
<script>
</script>
</body>
</html>

访问http://192.168.132.140:8888/app01/temp_test/

三 模板之标签 

标签看起来像是这样的: {% tag %}。标签比变量更加复杂:一些在输出中创建文本,一些通过循环或逻辑来控制流程,一些加载其后的变量将使用到的额外信息到模版中。一些标签需要开始和结束标签 (例如{% tag %} ...标签 内容 ... {% endtag %})。

3.1 for标签

遍历每一个元素:

[root@node10 mysite]# vim app01/views.py

#模板相关
import datetime
def temp_test(request):
        list1 = ["john","dachun","joy"]
        dict1 = {"name":"joy","Age":18}
        class A:
                def __init__(self,name,age):
                        self.name = name
                        self.age = age
                def test(self):
                        return "333666"
        a1 = A("john",18)
        a2 = A("dachun",20)
        a3 = A("joy",22)
        a_list = [a1,a2,a3]
        return render(request,"temp_test.html",{
                                                "list1":list1,
                                                "dict1":dict1,
                                                "a_list":a_list
                                                                })

[root@node10 mysite]# vim templates/temp_test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</script>
</head>
<body>
        <table border="1">
                <tr>
                        <th>姓名</th>
                        <th>年龄</th>
                </tr>
                {% for a in a_list%}
                        <tr>
                                <td>{{a.name}}</td>
                                <td>{{a.age}}</td>
                        </tr>
                {%endfor%}
        </table>
<script>
</script>
</body>
</html>

访问http://192.168.132.140:8888/app01/temp_test/

 

注:循环序号可以通过{{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

示例

[root@node10 mysite]# vim templates/temp_test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</script>
</head>
<body>
        <table border="1">
                <tr>
                        <th>序号</th>
                        <th>姓名</th>
                        <th>年龄</th>
                </tr>
                {% for a in a_list%}
                        <tr>
                                <td>{{forloop.counter}}</td>
                                <td>{{a.name}}</td>
                                <td>{{a.age}}</td>
                        </tr>
                {%endfor%}
        </table>
<script>
</script>
</body>
</html>

 访问http://192.168.132.140:8888/app01/temp_test/

 [root@node10 mysite]# vim templates/temp_test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</script>
</head>
<body>
        <table border="1">
                <tr>
                        <th>序号</th>
                        <th>姓名</th>
                        <th>年龄</th>
                </tr>
                {% for a in a_list%}
                        <tr>
                                <td>{{forloop.counter}}--{{forloop.first}}++{{forloop.last}}</td>
                                <td>{{a.name}}</td>
                                <td>{{a.age}}</td>
                        </tr>
                {%endfor%}
        </table>
<script>
</script>
</body>
</html>

 访问http://192.168.132.140:8888/app01/temp_test/

3.2 for ... empty

for 标签带有一个可选的{% empty %} 从句,以便在给出的组是空的或者没有被找到时,可以有所操作。

{% for person in person_list %}
    <p>{{ person.name }}</p>

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

3.3 if 标签

{% if %}会对一个变量求值,如果它的值是“True”(存在、不为空、且不是boolean类型的false值),对应的内容块会输出。

 [root@node10 mysite]# vim templates/temp_test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .green{
            background: green
        }
    </style>
</head>
<body>
        <table border="1">
                <tr>
                        <th>序号</th>
                        <th>姓名</th>
                        <th>年龄</th>
                </tr>
                {% for a in a_list%}
                        {% if forloop.last %}
                        <tr class="green">
                                <td>{{forloop.counter}}--{{forloop.first}}++{{forloop.last}}</td>
                                <td>{{a.name}}</td>
                                <td>{{a.age}}</td>
                        </tr>
                        {% else %}
                        <tr>
                                <td>{{forloop.counter}}--{{forloop.first}}++{{forloop.last}}</td>
                                <td>{{a.name}}</td>
                                <td>{{a.age}}</td>
                        {% endif %}
                {%endfor%}
        </table>
<script>
</script>
</body>
</html>

访问http://192.168.132.140:8888/app01/temp_test/

 [root@node10 mysite]# vim templates/temp_test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .green{
            background: green
        }
        .red{
            background: red
        }
    </style>
</head>
<body>
        <table border="1">
                <tr>
                        <th>序号</th>
                        <th>姓名</th>
                        <th>年龄</th>
                </tr>
                {% for a in a_list%}
                        {% if forloop.last %}
                        <tr class="green">
                                <td>{{forloop.counter}}--{{forloop.first}}++{{forloop.last}}</td>
                                <td>{{a.name}}</td>
                                <td>{{a.age}}</td>
                        </tr>
                        {% elif forloop.first %}
                        <tr class="red">
                                <td>{{forloop.counter}}--{{forloop.first}}++{{forloop.last}}</td>
                                <td>{{a.name}}</td>
                                <td>{{a.age}}</td>
                        </tr>
                        {%else%}
                        <tr>
                                <td>{{forloop.counter}}--{{forloop.first}}++{{forloop.last}}</td>
                                <td>{{a.name}}</td>
                                <td>{{a.age}}</td>
                        </tr>
                        {% endif %}
                {%endfor%}
        </table>
<script>
</script>
</body>
</html>

访问http://192.168.132.140:8888/app01/temp_test/

3.4 with

使用一个简单地名字缓存一个复杂的变量,当你需要使用一个“昂贵的”方法(比如访问数据库)很多次的时候是非常有用的

例如:

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

3.5 csrf_token

这个标签用于跨站请求伪造保护,这里再前面的setting.py已经注释掉了

打开

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

[root@node10 mysite]# vi templates/login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</script>
</head>
<body>
        <h3>用户登录</h3>
        <form action="" method="post">
                {%csrf_token%}
                <p>用户名:<input type="text" name="user"></p>
                <p>密   码:<input type="password" name="pwd"></p>
                <input type="submit">
        </form>
<script>
</script>
</body>
</html>

访问http://192.168.132.140:8888/app01/temp_test/

请求后,会多一个input标签,着个标签是一个随机字符串,用于校验,当login页面娜输入用户名和密码后,会带着返回的随机字符串,进行数据校验,确保值login页面发送的破石头请求

四 自定义标签和过滤器

1、在settings中的INSTALLED_APPS配置当前app,不然django无法找到自定义的simple_tag.这个已经完场

2、在app中创建templatetags模块(模块名只能是templatetags)

[root@node10 mysite]# mkdir app01/templatetags

3、创建任意 .py 文件,如:my_tags.py

[root@node10 mysite]# vim app01/templatetags/my_tags.py

from django import template
from django.utils.safestring import mark_safe
register = template.Library()   #register的名字是固定的,不可改变

@register.filter
def my_filter(v1,v2):
        return  v1 * v2

@register.simple_tag
def my_tag(v1,v2,v3):
    return  v1 * v2 * v3

@register.simple_tag
def my_input(pk,arg):
    result = "<input type='text' id='%s' class='%s' />" %(pk,arg,)
    return mark_safe(result)

4 html中导入my_tag文件,并引用

[root@node10 mysite]# vi templates/temp_test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .green{
            background: green
        }
        .red{
            background: red
        }
    </style>
</head>
<body>
{% load my_tags %} 
        <table border="1">
                <tr>
                        <th>序号</th>
                        <th>姓名</th>
                        <th>年龄</th>
                </tr>
                {% for a in a_list%}
                        {% if forloop.last %}
                        <tr class="green">
                                <td>{{forloop.counter}}--{{forloop.first}}++{{forloop.last}}</td>
                                <td>{{a.name}}</td>
                                <td>{{a.age}}</td>
                        </tr>
                        {% elif forloop.first %}
                        <tr class="red">
                                <td>{{forloop.counter}}--{{forloop.first}}++{{forloop.last}}</td>
                                <td>{{a.name}}</td>
                                <td>{{a.age}}</td>
                        </tr>
                        {%else%}
                        <tr>
                                <td>{{forloop.counter}}--{{forloop.first}}++{{forloop.last}}</td>
                                <td>{{a.name}}</td>
                                <td>{{a.age}}</td>
                        </tr>
                        {% endif %}
                {%endfor%}
        </table>
<hr>
<p>{{num|my_filter:2}}</p>
<hr>
<p>{% my_tag num 5 2 %}</p>
<hr>
<p>{% my_input 12 'green' %}</p>
<script>
</script>
</body>
</html>

访问http://192.168.132.140:8888/app01/temp_test/

注意:filter可以用在if等语句后,simple_tag不可以

{% if num|filter_multi:30 > 100 %}
    {{ num|filter_multi:30 }}
{% endif %}

五 模板继承 (extend)

Django模版引擎中最强大也是最复杂的部分就是模版继承了。模版继承可以让您创建一个基本的“骨架”模版,它包含您站点中的全部元素,并且可以定义能够被子模版覆盖的 blocks 。

通过从下面这个例子开始,可以容易的理解模版继承:

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{%/span> endblock %}</title>
</head>

<body>
    <div id="sidebar">
        {% block sidebar %}
        <ul>
            <li><a href="/">Home</a></li>
            <li><a href="/blog/">Blog</a></li>
        </ul>
        {% endblock %}
    </div>

    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>

这个模版,我们把它叫作 base.html, 它定义了一个可以用于两列排版页面的简单HTML骨架。“子模版”的工作是用它们的内容填充空的blocks。

在这个例子中, block 标签定义了三个可以被子模版内容填充的block。 block 告诉模版引擎: 子模版可能会覆盖掉模版中的这些位置。

子模版可能看起来是这样的:

{% extends "base.html" %}
 
{% block title %}My amazing blog{% endblock %}
 
{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}

extends 标签是这里的关键。它告诉模版引擎,这个模版“继承”了另一个模版。当模版系统处理这个模版时,首先,它将定位父模版——在此例中,就是“base.html”。

那时,模版引擎将注意到 base.html 中的三个 block 标签,并用子模版中的内容来替换这些block。根据 blog_entries 的值,输出可能看起来是这样的:

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="style.css" />
    <title>My amazing blog</title>
</head>
 
<body>
    <div id="sidebar">
        <ul>
            <li><a href="/">Home</a></li>
            <li><a href="/blog/">Blog</a></li>
        </ul>
    </div>
 
    <div id="content">
        <h2>Entry one</h2>
        <p>This is my first entry.</p>
 
        <h2>Entry two</h2>
        <p>This is my second entry.</p>
    </div>
</body>
</html>

请注意,子模版并没有定义 sidebar block,所以系统使用了父模版中的值。父模版的 {% block %} 标签中的内容总是被用作备选内容(fallback)。

这种方式使代码得到最大程度的复用,并且使得添加内容到共享的内容区域更加简单,例如,部分范围内的导航。

这里是使用继承的一些提示:

  • 如果你在模版中使用 {% extends %} 标签,它必须是模版中的第一个标签。其他的任何情况下,模版继承都将无法工作。

  • 在base模版中设置越多的 {% block %} 标签越好。请记住,子模版不必定义全部父模版中的blocks,所以,你可以在大多数blocks中填充合理的默认内容,然后,只定义你需要的那一个。多一点钩子总比少一点好。

  • 如果你发现你自己在大量的模版中复制内容,那可能意味着你应该把内容移动到父模版中的一个 {% block %} 中。

  • If you need to get the content of the block from the parent template, the {{ block.super }} variable will do the trick. This is useful if you want to add to the contents of a parent block instead of completely overriding it. Data inserted using {{ block.super }} will not be automatically escaped (see the next section), since it was already escaped, if necessary, in the parent template.

  • 为了更好的可读性,你也可以给你的 {% endblock %} 标签一个 名字 。例如:

{% block content %}
...
{% endblock content %} 
  • 在大型模版中,这个方法帮你清楚的看到哪一个  {% block %} 标签被关闭了。

  • 不能在一个模版中定义多个相同名字的 block 标签

图书后台管理案例

https://v3.bootcss.com/examples/dashboard/使用这个作为模板修改

在app02创建这个项目

[root@node10 mysite]# vim app02/urls.py

from django.urls import path,re_path
from app02 import views
urlpatterns = [
    path("test02/",views.test02, name="test1"),
    path("book_list",views.book_list),

]

写视图函数

[root@node10 mysite]# vim app02/views.py

from django.shortcuts import render,HttpResponse
from django.urls import reverse


# Create your views here.

def test02(request):
        return HttpResponse("this is app02's test function")
def book_list(request):
        return render(request,"book_list.html")

创建一个静态文件路径

[root@node10 mysite]# mkdir -p statics/css statics/js statics/plugins statics/images

[root@node10 mysite]# ll statics/

drwxr-xr-x 2 root root 6 Apr  2 10:53 css
drwxr-xr-x 2 root root 6 Apr  2 10:53 images
drwxr-xr-x 2 root root 6 Apr  2 10:53 js
drwxr-xr-x 2 root root 6 Apr  2 10:53 plugins

配置setting.py。引入这个路径

[root@node10 mysite]# vim mysite/settings.py

STATIC_URL = '/static/'   #这里是url别名
STATICFILES_DIRS = [
        os.path.join(BASE_DIR,"statics")
]
     

 

 

把这个文件复制到index.css里

[root@node10 mysite]# vim statics/css/index.css

/*
 * Base structure
 */

/* Move down content because we have a fixed navbar that is 50px tall */
body {
  padding-top: 50px;
}


/*
 * Global add-ons
 */

.sub-header {
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

/*
 * Top navigation
 * Hide default border to remove 1px line.
 */
.navbar-fixed-top {
  border: 0;
}

/*
 * Sidebar
 */

/* Hide for mobile, show later */
.sidebar {
  display: none;
}
@media (min-width: 768px) {
  .sidebar {
    position: fixed;
    top: 51px;
    bottom: 0;
    left: 0;
    z-index: 1000;
    display: block;
    padding: 20px;
    overflow-x: hidden;
    overflow-y: auto; /* Scrollable contents if viewport is shorter than content. */
    background-color: #f5f5f5;
    border-right: 1px solid #eee;
  }
}

/* Sidebar navigation */
.nav-sidebar {
  margin-right: -21px; /* 20px padding + 1px border */
  margin-bottom: 20px;
  margin-left: -20px;
}
.nav-sidebar > li > a {
  padding-right: 20px;
  padding-left: 20px;
}
.nav-sidebar > .active > a,
.nav-sidebar > .active > a:hover,
.nav-sidebar > .active > a:focus {
  color: #fff;
  background-color: #428bca;
}


/*
 * Main content
 */

.main {
  padding: 20px;
}
@media (min-width: 768px) {
  .main {
    padding-right: 40px;
    padding-left: 40px;
  }
}
.main .page-header {
  margin-top: 0;
}


/*
 * Placeholder dashboard ideas
 */

.placeholders {
  margin-bottom: 30px;
  text-align: center;
}
.placeholders h4 {
  margin-bottom: 0;
}
.placeholder {
  margin-bottom: 20px;
}
.placeholder img {
  display: inline-block;
  border-radius: 50%;
}
index.css

在html引入这个css

root@node10 mysite]# vi templates/book_list.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link res="stylesheet" href="/static/css/index.css">
</head>
<body>

    <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container-fluid">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Project name</a>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
          <ul class="nav navbar-nav navbar-right">
            <li><a href="#">Dashboard</a></li>
            <li><a href="#">Settings</a></li>
            <li><a href="#">Profile</a></li>
            <li><a href="#">Help</a></li>
          </ul>
          <form class="navbar-form navbar-right">
            <input type="text" class="form-control" placeholder="Search...">
          </form>
        </div>
      </div>
    </nav>

    <div class="container-fluid">
      <div class="row">
        <div class="col-sm-3 col-md-2 sidebar">
          <ul class="nav nav-sidebar">
            <li class="active"><a href="#">Overview <span class="sr-only">(current)</span></a></li>
            <li><a href="#">Reports</a></li>
            <li><a href="#">Analytics</a></li>
            <li><a href="#">Export</a></li>
          </ul>
          <ul class="nav nav-sidebar">
            <li><a href="">Nav item</a></li>
            <li><a href="">Nav item again</a></li>
            <li><a href="">One more nav</a></li>
            <li><a href="">Another nav item</a></li>
            <li><a href="">More navigation</a></li>
          </ul>
          <ul class="nav nav-sidebar">
            <li><a href="">Nav item again</a></li>
            <li><a href="">One more nav</a></li>
            <li><a href="">Another nav item</a></li>
          </ul>
        </div>
        <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
          <h1 class="page-header">Dashboard</h1>

          <div class="row placeholders">
            <div class="col-xs-6 col-sm-3 placeholder">
              <img src="data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" width="200" height="200" class="img-responsive" alt="Generic placeholder thumbnail">
              <h4>Label</h4>
              <span class="text-muted">Something else</span>
            </div>
            <div class="col-xs-6 col-sm-3 placeholder">
              <img src="data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" width="200" height="200" class="img-responsive" alt="Generic placeholder thumbnail">
              <h4>Label</h4>
              <span class="text-muted">Something else</span>
            </div>
            <div class="col-xs-6 col-sm-3 placeholder">
              <img src="data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" width="200" height="200" class="img-responsive" alt="Generic placeholder thumbnail">
              <h4>Label</h4>
              <span class="text-muted">Something else</span>
            </div>
            <div class="col-xs-6 col-sm-3 placeholder">
              <img src="data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" width="200" height="200" class="img-responsive" alt="Generic placeholder thumbnail">
              <h4>Label</h4>
              <span class="text-muted">Something else</span>
            </div>
          </div>

          <h2 class="sub-header">Section title</h2>
          <div class="table-responsive">
            <table class="table table-striped">
              <thead>
                <tr>
                  <th>#</th>
                  <th>Header</th>
                  <th>Header</th>
                  <th>Header</th>
                  <th>Header</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>1,001</td>
                  <td>Lorem</td>
                  <td>ipsum</td>
                  <td>dolor</td>
                  <td>sit</td>
                </tr>
                <tr>
                  <td>1,002</td>
                  <td>amet</td>
                  <td>consectetur</td>
                  <td>adipiscing</td>
                  <td>elit</td>
                </tr>
                <tr>
                  <td>1,003</td>
                  <td>Integer</td>
                  <td>nec</td>
                  <td>odio</td>
                  <td>Praesent</td>
                </tr>
                <tr>
                  <td>1,003</td>
                  <td>libero</td>
                  <td>Sed</td>
                  <td>cursus</td>
                  <td>ante</td>
                </tr>
                <tr>
                  <td>1,004</td>
                  <td>dapibus</td>
                  <td>diam</td>
                  <td>Sed</td>
                  <td>nisi</td>
                </tr>
                <tr>
                  <td>1,005</td>
                  <td>Nulla</td>
                  <td>quis</td>
                  <td>sem</td>
                  <td>at</td>
                </tr>
                <tr>
                  <td>1,006</td>
                  <td>nibh</td>
                  <td>elementum</td>
                  <td>imperdiet</td>
                  <td>Duis</td>
                </tr>
                <tr>
                  <td>1,007</td>
                  <td>sagittis</td>
                  <td>ipsum</td>
                  <td>Praesent</td>
                  <td>mauris</td>
                </tr>
                <tr>
                  <td>1,008</td>
                  <td>Fusce</td>
                  <td>nec</td>
                  <td>tellus</td>
                  <td>sed</td>
                </tr>
                <tr>
                  <td>1,009</td>
                  <td>augue</td>
                  <td>semper</td>
                  <td>porta</td>
                  <td>Mauris</td>
                </tr>
                <tr>
                  <td>1,010</td>
                  <td>massa</td>
                  <td>Vestibulum</td>
                  <td>lacinia</td>
                  <td>arcu</td>
                </tr>
                <tr>
                  <td>1,011</td>
                  <td>eget</td>
                  <td>nulla</td>
                  <td>Class</td>
                  <td>aptent</td>
                </tr>
                <tr>
                  <td>1,012</td>
                  <td>taciti</td>
                  <td>sociosqu</td>
                  <td>ad</td>
                  <td>litora</td>
                </tr>
                <tr>
                  <td>1,013</td>
                  <td>torquent</td>
                  <td>per</td>
                  <td>conubia</td>
                  <td>nostra</td>
                </tr>
                <tr>
                  <td>1,014</td>
                  <td>per</td>
                  <td>inceptos</td>
                  <td>himenaeos</td>
                  <td>Curabitur</td>
                </tr>
                <tr>
                  <td>1,015</td>
                  <td>sodales</td>
                  <td>ligula</td>
                  <td>in</td>
                  <td>libero</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
</body>
</html>
book_list.html

这里面引入两个css文件

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="/static/css/index.css">       #这里是static,是因为在setting.py里面的别名设置的是static

修改一下html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="/static/css/index.css">
</head>
<body>

    <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container-fluid">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">图书管理系统</a>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
          <ul class="nav navbar-nav navbar-right">
            <li><a href="#">Dashboard</a></li>
            <li><a href="#">Settings</a></li>
            <li><a href="#">Profile</a></li>
            <li><a href="#">Help</a></li>
          </ul>
          <form class="navbar-form navbar-right">
            <input type="text" class="form-control" placeholder="Search...">
          </form>
        </div>
      </div>
    </nav>

    <div class="container-fluid">
      <div class="row">
        <div class="col-sm-3 col-md-2 sidebar">
          <ul class="nav nav-sidebar">
            <li class="active"><a href="#">Overview <span class="sr-only">(current)</span></a></li>
            <li><a href="#">Reports</a></li>
            <li><a href="#">Analytics</a></li>
            <li><a href="#">Export</a></li>
          </ul>
          <ul class="nav nav-sidebar">
            <li><a href="">Nav item</a></li>
            <li><a href="">Nav item again</a></li>
            <li><a href="">One more nav</a></li>
            <li><a href="">Another nav item</a></li>
            <li><a href="">More navigation</a></li>
          </ul>
          <ul class="nav nav-sidebar">
            <li><a href="">Nav item again</a></li>
            <li><a href="">One more nav</a></li>
            <li><a href="">Another nav item</a></li>
          </ul>
        </div>
        <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
          <h2 class="sub-header">图书列表</h2>
          <div class="table-responsive">
            <table class="table table-striped">
              <thead>
                <tr>
                  <th>#</th>
                  <th>Header</th>
                  <th>Header</th>
                  <th>Header</th>
                  <th>Header</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>1,001</td>
                  <td>Lorem</td>
                  <td>ipsum</td>
                  <td>dolor</td>
                  <td>sit</td>
                </tr>
                <tr>
                  <td>1,002</td>
                  <td>amet</td>
                  <td>consectetur</td>
                  <td>adipiscing</td>
                  <td>elit</td>
                </tr>
                <tr>
                  <td>1,003</td>
                  <td>Integer</td>
                  <td>nec</td>
                  <td>odio</td>
                  <td>Praesent</td>
                </tr>
                <tr>
                  <td>1,003</td>
                  <td>libero</td>
                  <td>Sed</td>
                  <td>cursus</td>
                  <td>ante</td>
                </tr>
                <tr>
                  <td>1,004</td>
                  <td>dapibus</td>
                  <td>diam</td>
                  <td>Sed</td>
                  <td>nisi</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
</body>
</html>

 

访问http://192.168.132.140:8888/app02/book_list

 

 

 

 添加一个图书出版页面

[root@node10 mysite]# vim app02/urls.py

from django.urls import path,re_path
from app02 import views
urlpatterns = [
    path("test02/",views.test02, name="test1"),
    path("book_list/",views.book_list),
    path("publish_list/",views.publish_list),
]

[root@node10 mysite]# vim app02/views.py

from django.shortcuts import render,HttpResponse
from django.urls import reverse
# Create your views here.
def test02(request):
        return HttpResponse("this is app02's test function")
def book_list(request):
        return render(request,"book_list.html")
def publish_list(request):
        return render(request,"publish_list.html")

html文件

[root@node10 mysite]# vi templates/publish_list.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="/static/css/index.css">
</head>
<body>

    <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container-fluid">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">图书管理系统</a>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
          <ul class="nav navbar-nav navbar-right">
            <li><a href="#">Dashboard</a></li>
            <li><a href="#">Settings</a></li>
            <li><a href="#">Profile</a></li>
            <li><a href="#">Help</a></li>
          </ul>
          <form class="navbar-form navbar-right">
            <input type="text" class="form-control" placeholder="Search...">
          </form>
        </div>
      </div>
    </nav>

    <div class="container-fluid">
      <div class="row">
        <div class="col-sm-3 col-md-2 sidebar">
          <ul class="nav nav-sidebar">
            <li class="active"><a href="/app02/book_list/">图书管理<span class="sr-only">(current)</span></a></li>
            <li><a href="/app02/publish_list/">出版社管理</a></li>
            <li><a href="#">Analytics</a></li>
            <li><a href="#">Export</a></li>
          </ul>
        </div>
        <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
          <h2 class="sub-header">出版社列表</h2>
          <div class="table-responsive">
            <table class="table table-striped">
              <thead>
                <tr>
                  <th>#</th>
                  <th>Header</th>
                  <th>Header</th>
                  <th>Header</th>
                  <th>Header</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>1,001</td>
                  <td>Lorem</td>
                  <td>ipsum</td>
                  <td>dolor</td>
                  <td>sit</td>
                </tr>
                <tr>
                  <td>1,002</td>
                  <td>amet</td>
                  <td>consectetur</td>
                  <td>adipiscing</td>
                  <td>elit</td>
                </tr>
                <tr>
                  <td>1,003</td>
                  <td>Integer</td>
                  <td>nec</td>
                  <td>odio</td>
                  <td>Praesent</td>
                </tr>
                <tr>
                  <td>1,003</td>
                  <td>libero</td>
                  <td>Sed</td>
                  <td>cursus</td>
                  <td>ante</td>
                </tr>
                <tr>
                  <td>1,004</td>
                  <td>dapibus</td>
                  <td>diam</td>
                  <td>Sed</td>
                  <td>nisi</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
</body>
</html>

提取公共部分

[root@node10 mysite]# vim templates/base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="/static/css/index.css">
</head>
<body>

    <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container-fluid">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">图书管理系统</a>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
          <ul class="nav navbar-nav navbar-right">
            <li><a href="#">Dashboard</a></li>
            <li><a href="#">Settings</a></li>
            <li><a href="#">Profile</a></li>
            <li><a href="#">Help</a></li>
          </ul>
          <form class="navbar-form navbar-right">
            <input type="text" class="form-control" placeholder="Search...">
          </form>
        </div>
      </div>
    </nav>

    <div class="container-fluid">
      <div class="row">
        <div class="col-sm-3 col-md-2 sidebar">
          <ul class="nav nav-sidebar">
          {% block nv%}
          {% endblock nv%}
          </ul>
        </div>
        <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
        {% block content %}
        {% endblock content %}
        </div>
      </div>
    </div>
</body>
</html>

修改book_list.html

[root@node10 mysite]# vim templates/book_list.html

{% extends "base.html" %}
{% block nv%}
    <li class="active"><a href="/app02/book_list/">图书管理<span class="sr-only">(current)</span></a></li>
    <li><a href="/app02/publish_list/">出版社管理</a></li>
    <li><a href="/app02/author_list">作者管理</a></li>
{% endblock nv%}

{% block content %}
          <h2 class="sub-header">图书列表</h2>
          <div class="table-responsive">
            <table class="table table-striped">
              <thead>
                <tr>
                  <th>#</th>
                  <th>Header</th>
                  <th>Header</th>
                  <th>Header</th>
                  <th>Header</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>1,001</td>
                  <td>Lorem</td>
                  <td>ipsum</td>
                  <td>dolor</td>
                  <td>sit</td>
                </tr>
                <tr>
                  <td>1,002</td>
                  <td>amet</td>
                  <td>consectetur</td>
                  <td>adipiscing</td>
                  <td>elit</td>
                </tr>
                <tr>
                  <td>1,003</td>
                  <td>Integer</td>
                  <td>nec</td>
                  <td>odio</td>
                  <td>Praesent</td>
                </tr>
                <tr>
                  <td>1,003</td>
                  <td>libero</td>
                  <td>Sed</td>
                  <td>cursus</td>
                  <td>ante</td>
                </tr>
                <tr>
                  <td>1,004</td>
                  <td>dapibus</td>
                  <td>diam</td>
                  <td>Sed</td>
                  <td>nisi</td>
                </tr>
              </tbody>
            </table>
          </div>
{% endblock content %}

[root@node10 mysite]# vim templates/publish_list.html

{% extends "base.html" %}
{% block nv%}
    <li ><a href="/app02/book_list/">图书管理<span class="sr-only">(current)</span></a></li>
    <li class="active"><a href="/app02/publish_list/">出版社管理</a></li>
    <li><a href="/app02/author_list">作者管理</a></li>
{% endblock nv%}

{% block content %}
          <h2 class="sub-header">出版社列表</h2>
          <div class="table-responsive">
            <table class="table table-striped">
              <thead>
                <tr>
                  <th>#</th>
                  <th>Header</th>
                  <th>Header</th>
                  <th>Header</th>
                  <th>Header</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>1,001</td>
                  <td>Lorem</td>
                  <td>ipsum</td>
                  <td>dolor</td>
                  <td>sit</td>
                </tr>
                <tr>
                  <td>1,002</td>
                  <td>amet</td>
                  <td>consectetur</td>
                  <td>adipiscing</td>
                  <td>elit</td>
                </tr>
                <tr>
                  <td>1,003</td>
                  <td>Integer</td>
                  <td>nec</td>
                  <td>odio</td>
                  <td>Praesent</td>
                </tr>
                <tr>
                  <td>1,003</td>
                  <td>libero</td>
                  <td>Sed</td>
                  <td>cursus</td>
                  <td>ante</td>
                </tr>
                <tr>
                  <td>1,004</td>
                  <td>dapibus</td>
                  <td>diam</td>
                  <td>Sed</td>
                  <td>nisi</td>
                </tr>
              </tbody>
            </table>
          </div>
{% endblock content %}
publish_list.html

[root@node10 mysite]# vim templates/author_list.html

{% extends "base.html" %}
{% block nv%}
    <li ><a href="/app02/book_list/">图书管理<span class="sr-only">(current)</span></a></li>
    <li><a href="/app02/publish_list/">出版社管理</a></li>
    <li class="active"><a href="/app02/author_list">作者管理</a></li>
{% endblock nv%}

{% block content %}
          <h2 class="sub-header">作者列表</h2>
          <div class="table-responsive">
            <table class="table table-striped">
              <thead>
                <tr>
                  <th>#</th>
                  <th>Header</th>
                  <th>Header</th>
                  <th>Header</th>
                  <th>Header</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>1,001</td>
                  <td>Lorem</td>
                  <td>ipsum</td>
                  <td>dolor</td>
                  <td>sit</td>
                </tr>
                <tr>
                  <td>1,002</td>
                  <td>amet</td>
                  <td>consectetur</td>
                  <td>adipiscing</td>
                  <td>elit</td>
                </tr>
                <tr>
                  <td>1,003</td>
                  <td>Integer</td>
                  <td>nec</td>
                  <td>odio</td>
                  <td>Praesent</td>
                </tr>
                <tr>
                  <td>1,003</td>
                  <td>libero</td>
                  <td>Sed</td>
                  <td>cursus</td>
                  <td>ante</td>
                </tr>
                <tr>
                  <td>1,004</td>
                  <td>dapibus</td>
                  <td>diam</td>
                  <td>Sed</td>
                  <td>nisi</td>
                </tr>
              </tbody>
            </table>
          </div>
{% endblock content %}
author_list.html

访问http://192.168.132.140:8888/app02/book_list/,点击出版社管理

改进base.html

增加css和js两个位置,方便自己的html使用自己的css样式或者js

[root@node10 mysite]# vim templates/base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="/static/css/index.css">
    {% block css %}
    {% endblock css %}
</head>
<body>

    <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container-fluid">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">图书管理系统</a>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
          <ul class="nav navbar-nav navbar-right">
            <li><a href="#">Dashboard</a></li>
            <li><a href="#">Settings</a></li>
            <li><a href="#">Profile</a></li>
            <li><a href="#">Help</a></li>
          </ul>
          <form class="navbar-form navbar-right">
            <input type="text" class="form-control" placeholder="Search...">
          </form>
        </div>
      </div>
    </nav>

    <div class="container-fluid">
      <div class="row">
        <div class="col-sm-3 col-md-2 sidebar">
          <ul class="nav nav-sidebar">
          {% block nv%}
          {% endblock nv%}
          </ul>
        </div>
        <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
        {% block content %}
                <a href="#"><button class="btn btn-success">新增书籍</button></a>      #这里并不会显示,需要使用{{bloack.supper}}
        {% endblock content %}
        </div>
      </div>
    </div>
    {% block js %}
    {% endblock js %}
</body>
</html>

修改book_list.html

{% extends "base.html" %}
{% block nv%}
    <li class="active"><a href="/app02/book_list/">图书管理<span class="sr-only">(current)</span></a></li>
    <li><a href="/app02/publish_list/">出版社管理</a></li>
    <li><a href="/app02/author_list">作者管理</a></li>
{% endblock nv%}

{% block content %}
          <h2 class="sub-header">图书列表</h2>
          {{block.super}}
          <div class="table-responsive">
            <table class="table table-striped">
              <thead>
                <tr>
                  <th>#</th>
                  <th>Header</th>
                  <th>Header</th>
                  <th>Header</th>
                  <th>Header</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>1,001</td>
                  <td>Lorem</td>
                  <td>ipsum</td>
                  <td>dolor</td>
                  <td>sit</td>
                </tr>
                <tr>
                  <td>1,002</td>
                  <td>amet</td>
                  <td>consectetur</td>
                  <td>adipiscing</td>
                  <td>elit</td>
                </tr>
                <tr>
                  <td>1,003</td>
                  <td>Integer</td>
                  <td>nec</td>
                  <td>odio</td>
                  <td>Praesent</td>
                </tr>
                <tr>
                  <td>1,003</td>
                  <td>libero</td>
                  <td>Sed</td>
                  <td>cursus</td>
                  <td>ante</td>
                </tr>
                <tr>
                  <td>1,004</td>
                  <td>dapibus</td>
                  <td>diam</td>
                  <td>Sed</td>
                  <td>nisi</td>
                </tr>
              </tbody>
            </table>
          </div>
{% endblock content %}

访问http://192.168.132.140:8888/app02/book_list/

待续

 

posted @ 2020-04-03 10:13  梦中泪  阅读(1772)  评论(0编辑  收藏  举报