django——inclusion_tag


inclusion_tag()

原型: django.template.Library.inclusion_tag() 

主要作用:通過渲染一個模板來顯示一些數據

例如,Django的Admin界面使用自定義模板標簽顯示"添加/更改"表單頁面底部的按鈕。這些按鈕看起來總是相同,但鏈接的目標卻是根據正在編輯的對象而變化的。

這種類型的標簽被稱為"Inclusion 標簽",屬於自定義標簽的一種。

項目實例:

在我的一個blog項目中,一個博主的主頁面的左側欄和查看博主某篇文章的頁面的左柵欄的一樣的。為了不用重復寫同樣的代碼。且提高頁面的擴展性。我的bbs的左側欄就用了inclusion_tag來實現。

 

1.目錄結構

在項目blog這個app下面創建一個 templatetags 文夾。這個文件夾的名字必須是 templatetags 來命名的。然后在此文件夾下自定義一個 mytag.py 文件。

2. mytag.py:

這一個就是來處理不同數據的函數,返回的結果一致。

from django import template from django.db.models import Count from blog import models register = template.Library() @register.inclusion_tag('classfication.html') def get_calssfication_style(username): user = models.UserInfo.objects.filter(username=username).first() print(user.username) blog=user.blog nblog_id = user.blog_id print(nblog_id) cate_list = models.Category.objects.filter(blog_id=nblog_id).values("pk").annotate(c=Count("article__title")).values_list( "title", "c") print(cate_list) tag_list = models.Tag.objects.filter(blog_id=nblog_id).values("pk").annotate(c=Count("article")).values_list("title", "c") date_list = models.Article.objects.filter(user=user).extra( select={"y_m_date": "date_format(create_time,'%%Y/%%m')"}).values("y_m_date").annotate( c=Count("nid")).values_list("y_m_date", "c") return {"blog": blog, "cate_list": cate_list, "date_list": date_list, "tag_list": tag_list,"username":username}
View Code

3. classfication.html:

用來渲染mytag.py所返回的數據

 <div>
    <div class="panel panel-warning">
                <div class="panel-heading">我的標簽</div>
                <div class="panel-body"> {% for tag in tag_list %} {% if username %} {# <p><a href= "{{ username }}/tag/{{ tag.0 }}">{{ tag.0 }}({{ tag.1 }})</a></p>#}
                        <p><a href= "{% url 'blog_info' username=username condition='tag' param=tag.0 %}">{{ tag.0 }}({{ tag.1 }})</a></p> {% endif %} {% endfor %} </div>
            </div>

    <div class="panel panel-danger">
        <div class="panel-heading">隨筆分類</div>
        <div class="panel-body"> {% for cate in cate_list %} <p><a href="/{{ username }}/category/{{ cate.0 }}">{{ cate.0 }}({{ cate.1 }})</a></p> {% endfor %} </div>
    </div>

    <div class="panel panel-success">
        <div class="panel-heading">隨筆歸檔</div>
        <div class="panel-body"> {% for date in date_list %} <p><a href="/{{ username }}/archive/{{ date.0 }}">{{ date.0 }}({{ date.1 }})</a></p> {% endfor %} </div>
    </div>
 </div>
View Code

4. base.html:

這里我需要在 base.html 中引用上面的 classfication.html ,只需要在合適的地方加入以下兩行代碼:

 {% load mytag %} {% left_panel username %}

上面的代碼中 username 是一個參數。

 

ps:目前我的這個項目已經部署到ECS,可以訪問查看項目詳情,歡迎留言!geek

 


免責聲明!

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



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