目的
组合搜索实现如下图功能
知识点
1.使用自定义标签模板(templatetags)
实现
models.py 和 views.py和初级篇一样
重点如下:在app01目录下创建templatetags文件夹,并且创建一个.py文件,我创建了filter.py文件
1 # 需要在模版中注册 2 from django import template 3 from django.utils.safestring import mark_safe 4 register = template.Library() 5 @register.simple_tag 6 def filter_all(arg_dict,k): 7 ''' 8 {% if arg_dict.article_type_id == 0 %} 9 10 {% else %} 11 <a href="/article-0-{{ arg_dict.category_id }}.html">全部</a> 12 {% endif %} 13 ''' 14 ret = "" 15 if k == 'article_type_id': 16 n1 = arg_dict[k] 17 n2 = arg_dict['category_id'] 18 if n1 == 0: 19 ret = '<a class="active" href="/article-0-%s.html">全部</a>' % n2 20 else: 21 ret = '<a href="/article-0-%s.html">全部</a>' % n2 22 else: 23 n1 = arg_dict[k] 24 n2 = arg_dict['article_type_id'] 25 if n1 == 0: 26 ret = '<a class="active" href="/article-%s-0.html">全部</a>' % n2 27 else: 28 ret = '<a href="/article-%s-0.html">全部</a>' % n2 29 30 return mark_safe(ret) 31 32 @register.simple_tag 33 def filter_article_type(article_type_list,arg_dict,k): 34 ''' 35 {% for row in article_type_list %} 36 {% if row.id == arg_dict.article_type_id %} 37 <a class="active" href="/article-{{ row.id }}-{{ arg_dict.category_id }}.html">{{ row.caption }}</a> 38 {% else %} 39 <a href="/article-{{ row.id }}-{{ arg_dict.category_id }}.html">{{ row.caption }}</a> 40 {% endif %} 41 {% endfor %} 42 ''' 43 ret = [] 44 for row in article_type_list: 45 if k=='article_type_id': 46 if row.id == arg_dict['article_type_id']: 47 temp = '<a class="active" href="/article-%s-%s.html">%s</a>' % (row.id, arg_dict["category_id"], row.caption) 48 else: 49 temp = '<a href="/article-%s-%s.html">%s</a>' % (row.id, arg_dict["category_id"], row.caption) 50 else: 51 if row.id == arg_dict['category_id']: 52 temp = '<a class="active" href="/article-%s-%s.html">%s</a>' % ( arg_dict["article_type_id"],row.id, row.caption) 53 else: 54 temp = '<a href="/article-%s-%s.html">%s</a>' % ( arg_dict["article_type_id"],row.id, row.caption) 55 ret.append(temp) 56 return mark_safe("".join(ret))
修改html文件
article.html
1 {% load filter %} 2 <!DOCTYPE html> 3 <html lang="en"> 4 <head> 5 <meta charset="UTF-8"> 6 <title>Title</title> 7 <style> 8 .condition a{ 9 display:inline-block;; 10 padding: 3px 5px; 11 border:1px solid #dddddd; 12 margin:5px 5px; 13 } 14 .condition a.active{ 15 background-color: darkgreen; 16 } 17 </style> 18 </head> 19 <body> 20 <h1>过滤条件</h1> 21 <div class="condition"> 22 {% filter_all arg_dict 'article_type_id' %} 23 {% filter_article_type category_list arg_dict 'article_type_id' %} 24 25 </div> 26 <div class="condition"> 27 {% filter_all arg_dict 'category_id' %} 28 {% filter_article_type category_list arg_dict 'category_id' %} 29 30 </div> 31 <h1>查询结果</h1> 32 <ul> 33 {% for row in result %} 34 <li>{{ row.id }}-{{ row.title }}</li> 35 {% endfor %} 36 </ul> 37 </body> 38 </html>