【Python之路】特別篇--組合搜索功能實現

組合搜索:javascript

  根據特定標籤內容,返回符合的數據。html

效果圖:前端

 

設計規劃:java

1、數據庫表劃分:python

1.方向表,(運維自動化,Python開發,。。)正則表達式

2.分類表,(Python,Java,C#,。)數據庫

3.多對多,方向與分類外鍵表,django

4.視頻表,(視頻1,視頻2,。。。)json

2、表間關係:app

方向表與分類表:爲多對多關係,

1個方向能夠有多種分類,1個分類能夠同時對應多個方向。

分類表與視頻表:一對多關係,

1個分類能夠有多個視頻。

3、表內詳細設計:

方向表:

class Direction(models.Model):
    weight = models.IntegerField(verbose_name='權重(按從大到小排列)', default=0)
    name = models.CharField(verbose_name='名稱', max_length=32)
    classification = models.ManyToManyField('Classification')

    class Meta:
        db_table = 'Direction'
        verbose_name_plural = u'方向(視頻方向)'
    def __str__(self):
        return self.name

classfication爲方向表(Direction)多對多關係字段;

分類表:

class Classification(models.Model):
    weight = models.IntegerField(verbose_name='權重(按從大到小排列)', default=0)
    name = models.CharField(verbose_name='名稱', max_length=32)

    class Meta:
        db_table = 'Classification'
        verbose_name_plural = u'分類(視頻分類)'

    def __str__(self):
        return self.name
View Code

視頻表:

class Video(models.Model):

    status_choice = (
        (0, u'下線'),
        (1, u'上線'),
    )
    level_choice = (
        (1, u'初級'),
        (2, u'中級'),
        (3, u'高級'),
    )
    status = models.IntegerField(verbose_name='狀態', choices=status_choice, default=1)
    level = models.IntegerField(verbose_name='級別', choices=level_choice, default=1)
    classification = models.ForeignKey('Classification', null=True, blank=True)

    weight = models.IntegerField(verbose_name='權重(按從大到小排列)', default=0)

    title = models.CharField(verbose_name='標題', max_length=32)
    summary = models.CharField(verbose_name='簡介', max_length=32)
    img = models.ImageField(verbose_name='圖片', upload_to='./static/images/Video/')
    href = models.CharField(verbose_name='視頻地址', max_length=256)

    create_date = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'Video'
        verbose_name_plural = u'視頻'

    def __str__(self):
        return self.title
View Code

level爲等級字段,status爲視頻狀態字段;

 

具體效果:

經過對比其餘同類型的搜索示例發現,他們大多數都經過URL地址來向後臺傳遞類別 id 查詢數據庫,而後返回數據給前端頁面。

能夠發現:方向對應第一個數字,分類對應第二個數字,等級對應第三個數字。

方向的標籤代碼爲:

當點擊分類或等級時,其自身對應的id數字會發生改變,而另外兩個數字id不產生變化。

 

設計步驟:

1.咱們先設計出經過輸入網頁URL地址的方式,動態改變頁面標籤代碼中的值。

設計URL選擇器,正則表達式:

url(r'^video-(?P<direction_id>\d+)-(?P<classfication_id>\d+)-(?P<level_id>\d+).html', views.video),

direction_id 爲得到方向id,classfication_id爲得到分類id,level_id爲得到等級id

2.輸入url: /video-1-2-1.html 後參數傳遞給 views.video()函數處理。

def video(request,*args,**kwargs):
    current_url = request.path     #當前輸入網頁路徑 /video-0-0-0.html
    direction_id = int(kwargs.get('direction_id'))  #得到相應的id
    classfication_id = int(kwargs.get('classfication_id'))
    level_id = int(kwargs.get('level_id'))

接下來經過得到的id數據查詢數據庫信息;

此時,咱們得知數據庫中id字段是從1開始遞增,因此咱們設計當id=0 時爲得到所有數據。

1.當方向爲0時,表示直接從數據庫獲取全部的分類信息:

因爲,方向字段在網頁上表現爲永遠顯示所有數據。因此設計以下

def video(request,*args,**kwargs):
    # ...... 省略了部分
    # 得到全部方向信息:
    direction_list = models.Direction.objects.all().values('name','id')
    if direction_id != 0 :
        # 分類不等於0 即選擇了其中一個分類, /video-1-3-1.html
        # 取 url相對應的分類信息(根據 方向id 進行查詢,連表查詢)
        direction = models.Direction.objects.get(id=direction_id)
        classfication_list = direction.classification.values('name', 'id')
    else:
        classfication_list = models.Classification.objects.all().values('name','id')    #分類等於0 爲 所有, 直接取所有分類數據
    # 得到全部等級信息 
    # level_list = models.Video.level_choice
    ret = map(lambda x:{'name':x[1],'id':x[0]},models.Video.level_choice)
    level_list = list(ret)
    # 數據返回前端頁面
    return render(request,'video.html',{'direction_list':direction_list,'class_list':classfication_list,'level_list':level_list,'current_url':current_url})

其中,等級信息,存放在video表中的level字段中,以元組形式存放,爲了統一咱們將(元組,..)的形式 => [字典,..],使用了map()函數

向前端頁面返回了,方向,分類,等級的數據和當前url地址。 /video-1-3-1.html。

核心:前端接收到當前url地址後,經過模版語言simple_tag,動態的構造a標籤的href屬性,便可表現爲當改變url時,標籤href也同時發生改變

前端頁面:

<div>
    {% for item in direction_list %}
        {% simple_tag函數 current_url item %}
    {% endfor %}
</div>

3.設計simple_tag函數。

須要在項目app下建立 templatetags包, 而後自定義一個文件 xx.py

from django import template
from django.utils.safestring import mark_safe

register = template.Library()

@register.simple_tag
def action1(current_url, item):

    url_part_list = current_url.split('-')

    # 若是當前url中第一個位置 video-2-0-0.html
    if str(item['id']) == url_part_list[1]:
        temp = "<a href='%s' class='active'>%s</a>"
    else:
        temp = "<a href='%s'>%s</a>"

    url_part_list[1] = str(item['id'])

    ur_str = '-'.join(url_part_list)
    temp = temp %(ur_str, item['name'])
    return mark_safe(temp)

獲得了一個處理 方向 標籤的模板函數,方向、等級標籤的處理方式同上,只是url切割的位置稍有不一樣!

{% load newtag %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        a{
            display: inline-block;
            padding: 8px;
        }
        .active{
            background-color: coral;
            color: white;
        }
    </style>
</head>
<body>
    <h3>選擇:</h3>
    <div>
        {% for item in direction_list %}

             {% action1 current_url item %}
        {% endfor %}
    </div>
    <div>

        {% for item in class_list %}

            {% action2 current_url item %}
        {% endfor %}
    </div>
    <div>

        {% for item in level_list %}
            {% action3 current_url item %}
        {% endfor %}
    </div>
    <hr />
    <div>

    </div>
    <h3>視頻:</h3>
    <hr />

</body>
</html>
前端video.html
from django import template
from django.utils.safestring import mark_safe

register = template.Library()

@register.simple_tag
def action1(current_url, item):
    # videos-0-0-1.html
    # item: id name
    # video-   2   -0-0.html
    url_part_list = current_url.split('-')

    # 若是當前url中第一個位置 video-2-0-0.html
    if str(item['id']) == url_part_list[1]:
        temp = "<a href='%s' class='active'>%s</a>"
    else:
        temp = "<a href='%s'>%s</a>"

    url_part_list[1] = str(item['id'])

    ur_str = '-'.join(url_part_list)
    temp = temp %(ur_str, item['name'])
    return mark_safe(temp)
@register.simple_tag
def action2(current_url, item):
    # videos-0-0-1.html
    # item: id name
    url_part_list = current_url.split('-')

    # 若是當前url中第一個位置 video-2-0-0.html
    if str(item['id']) == url_part_list[2]:
        temp = "<a href='%s' class='active'>%s</a>"
    else:
        temp = "<a href='%s'>%s</a>"


    url_part_list[2] = str(item['id'])
    ur_str = '-'.join(url_part_list)
    temp = temp %(ur_str, item['name'])
    return mark_safe(temp)

@register.simple_tag
def action3(current_url, item):
    # videos-0-0-1.html
    # item: id name
    url_part_list = current_url.split('-')
    # 若是當前url中第三個位置 video-2-0-0.html
    if str(item['id']) == url_part_list[3].split('.')[0]:
        temp = "<a href='%s' class='active'>%s</a>"
    else:
        temp = "<a href='%s'>%s</a>"

    url_part_list[3] = str(item['id']) + '.html'

    ur_str = '-'.join(url_part_list)
    temp = temp %(ur_str, item['name'])
    return mark_safe(temp)
newtag.py

而後再設計一個在前端同時輸出, "所有" 的simple_tag函數

{% load newtag %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        a{
            display: inline-block;
            padding: 8px;
        }
        .active{
            background-color: coral;
            color: white;
        }
    </style>
</head>
<body>
    <h3>選擇:</h3>
    <div>
        {% action_all current_url 1 %} :
        {% for item in direction_list %}

             {% action1 current_url item %}
        {% endfor %}
    </div>
    <div>
        {% action_all current_url 2 %} :
        {% for item in class_list %}

            {% action2 current_url item %}
        {% endfor %}
    </div>
    <div>
        {% action_all current_url 3 %} :
        {% for item in level_list %}
            {% action3 current_url item %}
        {% endfor %}
    </div>
    <hr />
    <div>

    </div>
    <h3>視頻:</h3>
    <hr />

</body>
</html>
前端video.html
@register.simple_tag
def action_all_1(current_url):
    """
    獲取當前url,video-1-1-2.html
    :param current_url:
    :param item:
    :return:
    """
    url_part_list = current_url.split('-')
    if url_part_list[1] == "0":
        temp = "<a href='%s' class='active'>所有</a>"
    else:
        temp = "<a href='%s'>所有</a>"


    url_part_list[1] = "0"
    #  video 0 1 2.html
    href = '-'.join(url_part_list)

    temp = temp % (href,)
    return mark_safe(temp)

@register.simple_tag
def action_all_2(current_url):
    """
    獲取當前url,video-1-1-2.html
    :param current_url:
    :param item:
    :return:
    """
    url_part_list = current_url.split('-')

    if url_part_list[2] == "0":
        temp = "<a href='%s' class='active'>所有</a>"
    else:
        temp = "<a href='%s'>所有</a>"

    url_part_list[2] = "0"
    #  video 0 1 2.html
    href = '-'.join(url_part_list)

    temp = temp % (href,)
    return mark_safe(temp)

@register.simple_tag
def action_all_3(current_url):
    """
    獲取當前url,video-1-1-2.html
    :param current_url:
    :param item:
    :return:
    """
    url_part_list = current_url.split('-')
    #  video 0 1 2.html
    if url_part_list[3] == "0.html":
        temp = "<a href='%s' class='active'>所有</a>"
    else:
        temp = "<a href='%s'>所有</a>"

    url_part_list[3] = "0.html"

    href = '-'.join(url_part_list)

    temp = temp % (href,)
    return mark_safe(temp)
newtag.py

爲了下降simple_tag代碼過於冗餘,咱們用if..else統一歸類成一個函數:

{% load newtag %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        a{
            display: inline-block;
            padding: 8px;
            color: black;
            text-decoration: none;
        }
        .alt{
            color: black;
            font-weight: bolder;
        }
        .active{
            background-color: coral;
            color: white;
        }
        .item-list{
            margin: 6px;
        }
        .video-list{
            display: inline-block;
            margin: 6px;
        }
        .video-list img{
            height: 160px;
            width: 250px;
            border:0 ;
            overflow: hidden;
        }
    </style>
</head>
<body>
    <h3>選擇:</h3>
    <div class="item-list">
        <a href="javascript:;" class="alt">方向 :</a>
        {% action_all current_url 1 %}
        {% for item in direction_list %}
            {% action current_url item 1 %}
        {% endfor %}
    </div>
    <div class="item-list">
        <a href="javascript:;" class="alt">分類 :</a>
        {% action_all current_url 2 %}
        {% for item in class_list %}
            {% action current_url item 2 %}
        {% endfor %}
    </div>
    <div class="item-list">
        <a href="javascript:;" class="alt">等級 :</a>
        {% action_all current_url 3 %}
        {% for item in level_list %}
            {% action current_url item 3 %}
        {% endfor %}
    </div>
    <hr>

    <h3>視頻:</h3>
    <hr>

</body>
</html>
前端video.html
from django import template
from django.utils.safestring import mark_safe

register = template.Library()

@register.simple_tag
def action_all(current_url,index):
    url_split = current_url.split('-')
    if index == 3:
        if url_split[index] == '0.html':
            TEMP = '''
                     <a href='%s' class='active'>所有</a>
                '''
        else:
            TEMP = '''
                     <a href='%s'>所有</a>
                '''
        url_split[index] = '0.html'
    else:
        if url_split[index] == '0':
            TEMP = '''
                     <a href='%s' class='active'>所有</a>
                '''
        else:
            TEMP = '''
                     <a href='%s'>所有</a>
                '''
        url_split[index] = '0'
    url_str = '-'.join(url_split)
    TEMP = TEMP % (url_str)

    return mark_safe(TEMP)



@register.simple_tag
def action(current_url,item,index):
    url_split = current_url.split('-')
    if index == 3:
        if url_split[index].split('.')[0] == str(item['id']):
            TEMP = '''
                    <a href='%s' class='active'>%s</a>
                '''
        else:
            TEMP = '''
                    <a href='%s'>%s</a>
                '''
        url_split[index] = str(item['id']) + '.html'
    else:
        if url_split[index] == str(item['id']):
            TEMP = '''
                <a href='%s' class='active'>%s</a>
            '''
        else:
            TEMP = '''
                <a href='%s'>%s</a>
            '''
        url_split[index] = str(item['id'])
    url_str = '-'.join(url_split)
    TEMP = TEMP%(url_str,item['name'])
    return mark_safe(TEMP)
newtag.py

至此,咱們已經完成了 頁面上輸出所有的方向、分類、等級的數據,以及經過url地址改變更態修改了a標籤href代碼和添加了選中時特效。咱們還須要添加限制規則,規定當 方向 改變時,出現不一樣的分類!

4.進一步考慮添加規則!

當輸入的url中,方向id等於0 時,  => 顯示所有分類,  video-0-0-2.html

          不等於0 時,=>  if  分類id等於0  =>  分類根據 方向id 取出數據

                        不等於0 =>  分類根據 方向id 取出數據   當先輸入的url中,分類id沒有出如今經過查詢得到的分類id時,須要把分類id 置爲0。

def video(request,*args,**kwargs):

    current_url = request.path
    direction_id = int(kwargs.get('direction_id'))
    classfication_id = int(kwargs.get('classfication_id'))
    level_id = int(kwargs.get('level_id'))

    direction_list = models.Direction.objects.all().values('name','id')
    if direction_id == 0 :   # 方向 = 0
        # 分類所有顯示
        classfication_list = models.Classification.objects.all().values('name', 'id')
    else:
        # 方向 != 0 , 分類 根據方向,查詢
        if classfication_id == 0:
            # 分類爲0 ,根據url方向 取所有
            direction = models.Direction.objects.get(id=direction_id)
            classfication_list = direction.classification.values('name', 'id')
            classfication_id_list = list(map(lambda x: x['id'], classfication_list))
        else:
            # 分類不爲0 , 根據具體方向,取具體分類
            direction = models.Direction.objects.get(id=direction_id)
            classfication_list = direction.classification.values('name', 'id')
            classfication_id_list = list(map(lambda x: x['id'], classfication_list))

            if classfication_id in classfication_id_list:
                pass
            else:
                url_list = current_url.split('-')
                url_list[2] = '0'
                current_url = '-'.join(url_list)

    # 等級,統一格式,規範化輸出
    # level_list = models.Video.level_choice
    ret = map(lambda x:{'name':x[1],'id':x[0]},models.Video.level_choice)
    level_list = list(ret)

    return render(request,'video.html',{'direction_list':direction_list,
                                        'class_list':classfication_list,
                                        'level_list':level_list,
                                        'current_url':current_url,
                                        })
views.video()

5.最後考慮輸出視頻數據:

當方向、分類、等級id都爲0時,輸出所有的視頻;

當方向=0、分類!=0時,根據分類id查詢數據庫

當方向!=0、分類=0時,根據分類id查詢數據庫

當方向!=0、分類!=0時,根據分類id查詢數據庫

當等級!=0時, 根據分類id,等級id查詢數據庫                                

def video(request,*args,**kwargs):

    current_url = request.path
    direction_id = int(kwargs.get('direction_id'))
    classfication_id = int(kwargs.get('classfication_id'))
    level_id = int(kwargs.get('level_id'))

    q={}
    q['status'] = 1

    direction_list = models.Direction.objects.all().values('name','id')
    if direction_id == 0 :   # 方向 = 0
        # 分類所有顯示
        classfication_list = models.Classification.objects.all().values('name', 'id')
        if classfication_id == 0:
            # 方向所有,分類所有,視頻顯示所有
            pass
        else:
            # 方向所有,分類部分,視頻屬於分類下的
            q['classification__in'] = [classfication_id,]
    else:
        # 方向 != 0 , 分類 根據方向,查詢
        if classfication_id == 0:
            # 分類爲0 ,根據url方向 取所有
            direction = models.Direction.objects.get(id=direction_id)
            classfication_list = direction.classification.values('name', 'id')
            classfication_id_list = list(map(lambda x: x['id'], classfication_list))
            q['classification__in'] = classfication_id_list
        else:
            # 分類不爲0 , 根據具體方向,取具體分類下視頻
            direction = models.Direction.objects.get(id=direction_id)
            classfication_list = direction.classification.values('name', 'id')
            classfication_id_list = list(map(lambda x: x['id'], classfication_list))
            # 方向部分,分類部分,視頻屬於分類下的
            q['classification__in'] = [classfication_id,]

            if classfication_id in classfication_id_list:
                pass
            else:
                url_list = current_url.split('-')
                url_list[2] = '0'
                current_url = '-'.join(url_list)

    # 等級,統一格式,規範化輸出
    # level_list = models.Video.level_choice
    ret = map(lambda x:{'name':x[1],'id':x[0]},models.Video.level_choice)
    level_list = list(ret)

    # 若是選擇了等級 , 獲取id , 不然顯示所有
    if level_id != 0:
        q['level'] = level_id


    video_list = models.Video.objects.filter(**q).values('title','summary','img','href')

    return render(request,'video.html',{'direction_list':direction_list,
                                        'class_list':classfication_list,
                                        'level_list':level_list,
                                        'current_url':current_url,
                                        'video_list':video_list,
                                        })
views.video()

注意: 查詢時,能夠經過構造一個字典的方式添加查詢條件,返回最終結果。

q = {}
ret = models.X.objects.filter(**q).values('..,..')

 

最終效果圖:

完整代碼:

from django.shortcuts import render,HttpResponse
import json

# Create your views here.
from app01 import models
def video(request,*args,**kwargs):

    current_url = request.path
    direction_id = int(kwargs.get('direction_id'))
    classfication_id = int(kwargs.get('classfication_id'))
    level_id = int(kwargs.get('level_id'))

    q={}
    q['status'] = 1

    direction_list = models.Direction.objects.all().values('name','id')
    if direction_id == 0 :   # 方向 = 0
        # 分類所有顯示
        classfication_list = models.Classification.objects.all().values('name', 'id')
        if classfication_id == 0:
            # 方向所有,分類所有,視頻顯示所有
            pass
        else:
            # 方向所有,分類部分,視頻屬於分類下的
            q['classification__in'] = [classfication_id,]
    else:
        # 方向 != 0 , 分類 根據方向,查詢
        if classfication_id == 0:
            # 分類爲0 ,根據url方向 取所有
            direction = models.Direction.objects.get(id=direction_id)
            classfication_list = direction.classification.values('name', 'id')
            classfication_id_list = list(map(lambda x: x['id'], classfication_list))
            q['classification__in'] = classfication_id_list
        else:
            # 分類不爲0 , 根據具體方向,取具體分類下視頻
            direction = models.Direction.objects.get(id=direction_id)
            classfication_list = direction.classification.values('name', 'id')
            classfication_id_list = list(map(lambda x: x['id'], classfication_list))
            # 方向部分,分類部分,視頻屬於分類下的
            q['classification__in'] = [classfication_id,]

            if classfication_id in classfication_id_list:
                pass
            else:
                url_list = current_url.split('-')
                url_list[2] = '0'
                current_url = '-'.join(url_list)

    # 等級,統一格式,規範化輸出
    # level_list = models.Video.level_choice
    ret = map(lambda x:{'name':x[1],'id':x[0]},models.Video.level_choice)
    level_list = list(ret)

    # 若是選擇了等級 , 獲取id , 不然顯示所有
    if level_id != 0:
        q['level'] = level_id


    video_list = models.Video.objects.filter(**q).values('title','summary','img','href')

    return render(request,'video.html',{'direction_list':direction_list,
                                        'class_list':classfication_list,
                                        'level_list':level_list,
                                        'current_url':current_url,
                                        'video_list':video_list,
                                        })
後臺 views.py
from django.db import models

class Direction(models.Model):
    weight = models.IntegerField(verbose_name='權重(按從大到小排列)', default=0)
    name = models.CharField(verbose_name='名稱', max_length=32)

    classification = models.ManyToManyField('Classification')

    class Meta:
        db_table = 'Direction'
        verbose_name_plural = u'方向(視頻方向)'

    def __str__(self):
        return self.name


class Classification(models.Model):
    weight = models.IntegerField(verbose_name='權重(按從大到小排列)', default=0)
    name = models.CharField(verbose_name='名稱', max_length=32)

    class Meta:
        db_table = 'Classification'
        verbose_name_plural = u'分類(視頻分類)'

    def __str__(self):
        return self.name


class Video(models.Model):

    status_choice = (
        (0, u'下線'),
        (1, u'上線'),
    )
    level_choice = (
        (1, u'初級'),
        (2, u'中級'),
        (3, u'高級'),
    )
    status = models.IntegerField(verbose_name='狀態', choices=status_choice, default=1)
    level = models.IntegerField(verbose_name='級別', choices=level_choice, default=1)
    classification = models.ForeignKey('Classification', null=True, blank=True)

    weight = models.IntegerField(verbose_name='權重(按從大到小排列)', default=0)

    title = models.CharField(verbose_name='標題', max_length=32)
    summary = models.CharField(verbose_name='簡介', max_length=32)
    img = models.ImageField(verbose_name='圖片', upload_to='./static/images/Video/')
    href = models.CharField(verbose_name='視頻地址', max_length=256)

    create_date = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'Video'
        verbose_name_plural = u'視頻'

    def __str__(self):
        return self.title
後臺 models.py
# templatetags --newtag.py
#!/usr/bin/env python
# -*-coding:utf-8 -*-

from django import template
from django.utils.safestring import mark_safe

register = template.Library()

@register.simple_tag
def image_show(item,counter,allcount,remainder):
    '''
    :param item:   當前循環獲取的數據
    :param counter:  當前循環次數(模版語言for循環默認從1開始)
    :param allcount:  頁面分佈列數
    :param remainder: 餘數
    :return:
    '''

    TEMP = '''
     <div style="width: 245px;" >
            <img src="/%s" alt="" style="width: 245px;height: 250px">
            <p>%s</p>
            <p>%s</p>
    </div>
    '''
    if counter%allcount == remainder:
        TEMP = TEMP %(item['student__pic'],
                      item['student__name'],
                      item['letter_of_thanks'],
                      )
        return mark_safe(TEMP)
    else:
        return ''

@register.filter
def image_show2(value,arg):

    countet = value
    allcount = int(arg.split(',')[0])
    remainder = int(arg.split(',')[1])
    if countet%allcount == remainder:
        return True
    else:
        return False



@register.simple_tag
def action1(current_url,item):
    url_split = current_url.split('-')
    if url_split[1] == str(item['id']):
        TEMP = '''
            <a href='%s' class='active'>%s</a>
        '''
    else:
        TEMP = '''
            <a href='%s'>%s</a>
        '''
    url_split[1] = str(item['id'])
    url_str = '-'.join(url_split)
    TEMP = TEMP%(url_str,item['name'])

    return mark_safe(TEMP)

@register.simple_tag
def action2(current_url,item):
    url_split = current_url.split('-')
    if url_split[2] == str(item['id']):
        TEMP = '''
                <a href='%s' class='active'>%s</a>
            '''
    else:
        TEMP = '''
                <a href='%s'>%s</a>
            '''
    url_split[2] = str(item['id'])
    url_str = '-'.join(url_split)
    TEMP = TEMP%(url_str,item['name'])

    return mark_safe(TEMP)

@register.simple_tag
def action3(current_url,item):
    url_split = current_url.split('-')
    if url_split[3].split('.')[0] == str(item['id']):
        TEMP = '''
                <a href='%s' class='active'>%s</a>
            '''
    else:
        TEMP = '''
                <a href='%s'>%s</a>
            '''
    url_split[3] = str(item['id']) + '.html'
    url_str = '-'.join(url_split)
    TEMP = TEMP%(url_str,item['name'])

    return mark_safe(TEMP)

@register.simple_tag
def action_all_1(current_url):
    url_split = current_url.split('-')
    if url_split[1] == '0':
        TEMP = '''
                 <a href='%s' class='active'>所有</a>
            '''
    else:
        TEMP = '''
                 <a href='%s'>所有</a>
            '''
    url_split[1] = '0'
    url_str = '-'.join(url_split)
    TEMP = TEMP % (url_str)

    return mark_safe(TEMP)

@register.simple_tag
def action_all_2(current_url):
    url_split = current_url.split('-')
    if url_split[2] == '0':
        TEMP = '''
                 <a href='%s' class='active'>所有</a>
            '''
    else:
        TEMP = '''
                 <a href='%s'>所有</a>
            '''
    url_split[2] = '0'
    url_str = '-'.join(url_split)
    TEMP = TEMP % (url_str)

    return mark_safe(TEMP)

@register.simple_tag
def action_all_3(current_url):
    url_split = current_url.split('-')
    if url_split[3] == '0.html':
        TEMP = '''
                 <a href='%s' class='active'>所有</a>
            '''
    else:
        TEMP = '''
                 <a href='%s'>所有</a>
            '''
    url_split[3] = '0.html'
    url_str = '-'.join(url_split)
    TEMP = TEMP % (url_str)

    return mark_safe(TEMP)

@register.simple_tag
def action_all(current_url,index):
    url_split = current_url.split('-')
    if index == 3:
        if url_split[index] == '0.html':
            TEMP = '''
                     <a href='%s' class='active'>所有</a>
                '''
        else:
            TEMP = '''
                     <a href='%s'>所有</a>
                '''
        url_split[index] = '0.html'
    else:
        if url_split[index] == '0':
            TEMP = '''
                     <a href='%s' class='active'>所有</a>
                '''
        else:
            TEMP = '''
                     <a href='%s'>所有</a>
                '''
        url_split[index] = '0'
    url_str = '-'.join(url_split)
    TEMP = TEMP % (url_str)

    return mark_safe(TEMP)



@register.simple_tag
def action(current_url,item,index):
    url_split = current_url.split('-')
    if index == 3:
        if url_split[index].split('.')[0] == str(item['id']):
            TEMP = '''
                    <a href='%s' class='active'>%s</a>
                '''
        else:
            TEMP = '''
                    <a href='%s'>%s</a>
                '''
        url_split[index] = str(item['id']) + '.html'
    else:
        if url_split[index] == str(item['id']):
            TEMP = '''
                <a href='%s' class='active'>%s</a>
            '''
        else:
            TEMP = '''
                <a href='%s'>%s</a>
            '''
        url_split[index] = str(item['id'])
    url_str = '-'.join(url_split)
    TEMP = TEMP%(url_str,item['name'])
    return mark_safe(TEMP)
後臺 newtag.py
{% load newtag %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        a{
            display: inline-block;
            padding: 8px;
            color: black;
            text-decoration: none;
        }
        .alt{
            color: black;
            font-weight: bolder;
        }
        .active{
            background-color: coral;
            color: white;
        }
        .item-list{
            margin: 6px;
        }
        .video-list{
            display: inline-block;
            margin: 6px;
        }
        .video-list img{
            height: 160px;
            width: 250px;
            border:0 ;
            overflow: hidden;
        }
    </style>
</head>
<body>
    <h3>選擇:</h3>
    <div class="item-list">
        <a href="javascript:;" class="alt">方向 :</a>
        {% action_all current_url 1 %}
        {% for item in direction_list %}
            {% action current_url item 1 %}
        {% endfor %}
    </div>
    <div class="item-list">
        <a href="javascript:;" class="alt">分類 :</a>
        {% action_all current_url 2 %}
        {% for item in class_list %}
            {% action current_url item 2 %}
        {% endfor %}
    </div>
    <div class="item-list">
        <a href="javascript:;" class="alt">等級 :</a>
        {% action_all current_url 3 %}
        {% for item in level_list %}
            {% action current_url item 3 %}
        {% endfor %}
    </div>
    <hr>

    <h3>視頻:</h3>
    {% for item in video_list %}
        <a href="{{ item.href }}" class="video-list">
            <img src="{{ item.img }}" alt="">
            <p>{{ item.title }}</p>
            <p>{{ item.summary }}</p>
        </a>
    {% endfor %}
    <hr>

</body>
</html>
前端 video.html
相關文章
相關標籤/搜索