4.Django模板語言和分頁


繼承 extends

 子版只能繼承一個父模板

1.父模板 master.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %} {% endblock %}</title>
    <link rel="stylesheet" href="/static/common.css">
    <style>
        .pg-header{
            height: 50px;
            background-color: red;
            color:blue
        }
        {% block css %} {% endblock %}
    </style>
</head>
<body>
    <div class="pg-header">小男孩管理</div>

    {% block content %} {% endblock %}

    <div class="pg-footer"></div>

    <script src="/static/jquery-1.12.4.js"></script>

    {% block js %} {% endblock %}
</body>
</html>

2.子版繼承方法

{% extends 'master.html' %}     #引用母版

{% block title %}用戶管理{% endblock %}

{% block content %}
    <h1>用戶管理</h1>
    <ul>
        {% for i in u %}
        <li>{{ i }}</li>
        {% endfor %}
    </ul>
{% endblock %}

{% block css %}
    <style>
        body{
            background-color: black;
        }
    </style>
{% endblock %}

{% block js %}
    <script>

    </script>
{% endblock %}

導入定制的組件 include

 創建tag.html

在index.html中導入tag.html,可以導入很多個

{% include 'tag.html' %}

tag.html

form>
    <input type="text" name="user"/>
    <input type="submit" value="提交"/>
</form>

index.html

{# 指定繼承的模板 #}
{% extends 'master.html' %}
 
{# 指定替換的位置 #}
{% block title %}
    tp1
{% endblock %}
 
{# 指定替換的位置 #}
{% block content %}
    <p>tp1</p>
 
    {# 導入單獨組件 #}
    {% include 'tag.html' %}
{% endblock %}

simple_tag and filter

 1.django默認自帶方法

{{ item.event_start|date:"Y-m-d H:i:s"}}    #日期格式進行轉換
{{ bio|truncatewords:"30" }}                  #取字符串前30位
{{ my_list|first|upper }}                     #第一個字符大寫             
{{ name|lower }}                                #所有字符小寫

 2.simple_tag

第一步: 在app01下面創建templatetags(必須是這個名字)文件夾

第二步:在templatetags下面創建test1.py文件

第三步:模板中   首先在開頭要先導入  {%  load test1 %} 

第四步: 模板中使用方法   {%  函數名 參數1  參數2  %}

test1.py

from django import template
from django.utils.safestring import mark_safe
# 必須是register對象
register = template.Library()

@register.simple_tag def func(a1,a2): return a1 + a2

index.py

{% load test1 %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {{ name }}
    {{ name|lower }}

    {% func 2 5 %}
</body>
</html>

3.filter

test1.py

from django import template
from django.utils.safestring import mark_safe
# 必須是register對象
register = template.Library()

@register.simple_tag def func(a1,a2): return a1 + a2 @register.filter() def func1(b1,b2): return b1 + b2

index.py

{% load test1 %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {{ name }}
    {{ name|lower }}

{#    simpletag#}
    {% func 2 5 %}

{#    filter#}
    {{ 'zhang'|func1:'derek' }}


</body>
</html>

 總結:

simple:

優點:參數任意

缺點:不能作為if條件

filter

優點:最多兩個參數

缺點:可以作為if條件

 分頁

 1.簡單分頁

 涉及xss攻擊,需要用到mark_safe方法,使用此方法字符串傳輸到后端后,已html形式顯示,而非字符串

HTML文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .pagination .page{
            display: inline-block;
            padding: 5px;
            background-color: cyan;
            margin: 5px;
        }
        .pagination .page.active{
            background-color: brown;
            color: white;
        }
    </style>
</head>
<body>
    <ul>
        {% for item in li %}
            <li>{{ item }}</li>
        {% endfor %}
    </ul>
    <div class="pagination">
        {{ page_str }}
    </div>
</body>
</html>
user_list.html

views.py

from django.shortcuts import render,HttpResponse
from django.core.handlers.wsgi import WSGIRequest
from django.utils.safestring import mark_safe

LIST = []
for i in range(109):
    LIST.append(i)

from django.utils.safestring import  mark_safe
def user_list(request):
    current_page = request.GET.get('p',1)
    current_page = int(current_page)

    start = (current_page-1)*10
    end = current_page*10
    data = LIST[start:end]

    all_count = len(LIST)
    count,y = divmod(all_count,10)
    if y :
        count +=1

    page_list = []
    for i in range(1,count+1):
        if i == current_page:
            temp = '<a class="page active" href="/user_list/?p=%s">%s</a>'%(i,i)
        else:
            temp = '<a class="page" href="/user_list/?p=%s">%s</a>'%(i,i)

        page_list.append(temp)

    page_str = mark_safe(''.join(page_list))

    return render(request,'user_list.html',{'li':data,'page_str':page_str})

瀏覽器訪問地址

瀏覽器訪問地址:http://127.0.0.1:8000/user_list/?p=3

2.增加功能

分頁數進行定制,添加上一頁、下一頁,增加跳轉功能,實現分頁的完整功能

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .pagination .page{
            display: inline-block;
            padding: 5px;
            background-color: cyan;
            margin: 5px;
        }
        .pagination .page.active{
            background-color: brown;
            color: white;
        }
    </style>
</head>
<body>
    <ul>
        {% for item in li %}
            <li>{{ item }}</li>
        {% endfor %}
    </ul>
    <div class="pagination">
        {{ page_str }}
    </div>
</body>
</html>

user_list.html
user_list

views.py

LIST = []
for i in range(199):
    LIST.append(i)

from django.utils.safestring import  mark_safe
def user_list(request):
    current_page = request.GET.get('p',1)
    current_page = int(current_page)

    start = (current_page-1)*10
    end = current_page*10
    data = LIST[start:end]

    all_count = len(LIST)
    total_count,y = divmod(all_count,10)
    if y :
        total_count +=1
    pager_num = 11                          #頁碼數

    page_list = []
    if total_count < pager_num :            #總頁面小於頁碼數
        start_index = 1
        end_index = total_count + 1
    else:
        if current_page <= pager_num/2:     #開頭
            start_index = 1
            end_index = pager_num + 1
        elif current_page + (pager_num-1)/2 >= total_count:         #中間
            start_index = total_count - (pager_num-1)
            end_index = total_count + 1
        else:                               #結尾
            start_index = current_page - (pager_num-1)/2
            end_index = current_page + (pager_num-1)/2 + 1

    # 上下頁碼
    if current_page == 1:
        prev = '<a class="page" href="javascript:void(0)">上一頁</a>'  # 什么都不干
    else:
        prev =  '<a class="page" href="/user_list/?p=%s">上一頁</a>'%(current_page-1)
    page_list.append(prev)
    for i in range(int(start_index),int(end_index)):
        if i == current_page:
            temp = '<a class="page active" href="/user_list/?p=%s">%s</a>'%(i,i)
        else:
            temp = '<a class="page" href="/user_list/?p=%s">%s</a>'%(i,i)

        page_list.append(temp)
    if current_page == total_count:
        nex = '<a class="page" href="javascript:void(0)">下一頁</a>'  # 什么都不干
    else:
        nex = '<a class="page" href="/user_list/?p=%s">下一頁</a>'%(current_page+1)
    page_list.append(nex)

    # 跳轉 可以寫到前端
    jump = '''
    <input type="text" /><a onclick="jumpTo(this,'/user_list/?p=');">GO</a>
    <script>
        function jumpTo(ths,base) {
            var val = ths.previousSibling.value;
            location.href = base + val;
        }
    </script>
    '''
    page_list.append(jump)

    page_str = mark_safe(''.join(page_list))

    return render(request,'user_list.html',{'li':data,'page_str':page_str})

3.優化完善

頁碼代碼跟業務代碼分開,創建class類,然后views導入進去

app01下面創建 utils文件夾,里面創建pagination.py

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .pagination .page{
            display: inline-block;
            padding: 5px;
            background-color: cyan;
            margin: 5px;
        }
        .pagination .page.active{
            background-color: brown;
            color: white;
        }
    </style>
</head>
<body>
    <ul>
        {% for item in li %}
            <li>{{ item }}</li>
        {% endfor %}
    </ul>
    <div class="pagination">
        {{ page_str }}
    </div>
</body>
</html>

user_list.html
user_list.html

views.py

LIST = []
for i in range(199):
    LIST.append(i)

class Page:
    def __init__(self, current_page, data_count, per_page_count=10, pager_num=7):
        self.current_page = current_page
        self.data_count = data_count
        self.per_page_count = per_page_count
        self.pager_num = pager_num

    @property
    def start(self):
        return (self.current_page - 1) * self.per_page_count

    @property
    def end(self):
        return self.current_page * self.per_page_count

    @property
    def total_count(self):
        v, y = divmod(self.data_count, self.per_page_count)
        if y:
            v += 1
        return v

    def page_str(self, base_url):
        page_list = []

        if self.total_count < self.pager_num:
            start_index = 1
            end_index = self.total_count + 1
        else:
            if self.current_page <= (self.pager_num + 1) / 2:
                start_index = 1
                end_index = self.pager_num + 1
            else:
                start_index = self.current_page - (self.pager_num - 1) / 2
                end_index = self.current_page + (self.pager_num + 1) / 2
                if (self.current_page + (self.pager_num - 1) / 2) > self.total_count:
                    end_index = self.total_count + 1
                    start_index = self.total_count - self.pager_num + 1

        if self.current_page == 1:
            prev = '<a class="page" href="javascript:void(0);">上一頁</a>'
        else:
            prev = '<a class="page" href="%s?p=%s">上一頁</a>' % (base_url, self.current_page - 1,)
        page_list.append(prev)

        for i in range(int(start_index), int(end_index)):
            if i == self.current_page:
                temp = '<a class="page active" href="%s?p=%s">%s</a>' % (base_url, i, i)
            else:
                temp = '<a class="page" href="%s?p=%s">%s</a>' % (base_url, i, i)
            page_list.append(temp)

        if self.current_page == self.total_count:
            nex = '<a class="page" href="javascript:void(0);">下一頁</a>'
        else:
            nex = '<a class="page" href="%s?p=%s">下一頁</a>' % (base_url, self.current_page + 1,)
        page_list.append(nex)

        jump = """
        <input type='text'  /><a onclick='jumpTo(this, "%s?p=");'>GO</a>
        <script>
            function jumpTo(ths,base){
                var val = ths.previousSibling.value;
                location.href = base + val;
            }
        </script>
        """ % (base_url,)

        page_list.append(jump)

        page_str = mark_safe("".join(page_list))

        return page_str

from django.utils.safestring import  mark_safe
def user_list(request):
    current_page = request.GET.get('p', 1)
    current_page = int(current_page)
    page_obj = Page(current_page,len(LIST))

    data = LIST[page_obj.start:page_obj.end]

    page_str = page_obj.page_str("/user_list/")

    return render(request, 'user_list.html', {'li': data,'page_str': page_str})

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM