1. 程式人生 > >Django的inclusion_tag實現顯示最新發布的文章

Django的inclusion_tag實現顯示最新發布的文章

一 編輯mysite/article/templatetags/article_tags.py,增加自定義標籤

# template包含了很多與模板有關的類和方法
from django import template
# Library是template類的一個方法
# register包含了simple_tag方法
# 它將用於自定義標籤
register = template.Library()

from article.models import ArticlePost

# 表明下面的程式碼是自定義的simple_tag
@register.simple_tag
def total_articles():
    # 返回文章物件的查詢結果
    return ArticlePost.objects.count()

@register.simple_tag
def author_total_articles(user):
    # 返回某個作者的文章總數
    return user.article.count()

# 用裝飾器宣告自定義標籤,通過引數確定所渲染的模板檔案
@register.inclusion_tag('article/list/latest_articles.html')
# 在具體使用標籤時,會通過n傳參
def latest_articles(n=5):
    # 按照發布時間倒排序,排序個數由n來決定
    latest_articles = ArticlePost.objects.order_by("-created")[:n]
    return {"latest_articles": latest_articles}

二 新增模板檔案mysite/templates/article/list/latest_articles.html

<ul>
    {% for article in latest_articles %}
    <li>
        <a href="{{ article.get_url_path }}">{{ article.title }}</a>
    </li>
    {% endfor %}
</ul>

三 mysite/templates/article/list/article_detail.html引入定定義標籤

{% extends "base.html" %}
{% load staticfiles %}
{% load article_tags %}
{% block title %}{{ article.title }}{% endblock %}
{% block content %}
<!-- with發起一個賦值操作,它的結尾部分是endwith,total_likes分別為點贊使用者總數,total_likes在
這兩部分圈定的範圍內有效-->
{% with total_likes=article.users_like.count users_like=article.users_like.all %}

<div class="container">
    <div class="col-md-9">
        <header>
            <h1>{{ article.title }}</h1>
            <p>
                <a href="{% url 'article:author_articles' article.author.username %}">
                    {{ article.author.username }}
                </a>
                <!-- pluralize的作用:如果total_likes為0或複數,則顯示的是likes,如果total_likes為1,則顯示like-->
                <span style="margin-left:20px" class="glyphicon glyphicon-thumbs-up">{{ total_likes }}like{{ total_likes | pluralize }}</span>
                <!-- 該文章總的訪問此時-->
                <span style="margin-left: 20px">{{ total_views }}view{{ total_views | pluralize }}</span>
            </p>
        </header>

        <link rel="stylesheet" href="{% static 'editor/css/editormd.preview.css' %}"/>
        <div id='editormd-view'>
        <textarea id="append-test" style="display:none;">
{{ article.body }}
        </textarea>
        </div>
        <div>
            <!--點贊功能實現-->
            <p class="text-center">
                <a onclick="like_article({{article.id}}, 'like')" href="#"><span class="glyphicon glyphicon-thumbs-up">like</span></a>
                <a onclick="like_article({{article.id}}, 'unlike')" href="#"><span style="margin-left: 15px;"
                                                                                   class="glyphicon glyphicon-thumbs-down">unlike</span></a>
            </p>
        </div>
        <div>
            <p class="text-center"><strong>點贊本文的讀者</strong></p>
            {% for user in article.users_like.all %}
            <p class="text-center">{{ user.username }}</p>
            {% empty %}
            <p class="text-center">還沒有人對此文章表態</p>
            {% endfor %}
        </div>
        <!--以下是評論功能-->
        <hr>
        <div>
            <h3><span class="glyphicon glyphicon-bullhorn"></span>本文有{{ article.comments.count }}評論</h3>
            {% for comment in article.comments.all %}
            <div>
                <p><strong>{{ comment.commentator }}</strong>說:</p>
                <p style="margin-left:40px;">{{ comment.body }}</p>
            </div>
            {% empty %}
            <p>沒有評論</p>
            {% endfor %}

            <h3><span class="glyphicon glyphicon-send"></span>看文章,發評論,不要沉默</h3>
            <form action="." method="post" class="form-horizontal" role="form">{% csrf_token %}
                <div class="form-group">
                    <label for="inputEmail3" class="col-sm-2 control-label">評論員</label>
                    <div class="col-sm-10">
                        {{ comment_form.commentator}}
                    </div>
                </div>
                <div class="form-group">
                    <label for="inputEmail3" class="col-sm-2 control-label">評論</label>
                    <div class="col-sm-10">
                        {{ comment_form.body }}
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <p><input type="submit" name="" value="發評論" class="btn btn-primary"></p>
                    </div>
                </div>
            </form>
        </div>
    </div>
    <div class="col-md-3">
        <p class="text-center">
        <h3>最受歡迎文章</h3></p>
        <ol>
            {% for article_rank in most_viewed %}
            <li>
                <a href="{{article_rank.get_url_path}}">{{ article_rank.title }}</a>
            </li>
            {% endfor %}
        </ol>
        <hr>
        <p class="text-center">
        <h3>最新文章</h3></p>
        <div>{% latest_articles 4 %}</div>
    </div>
</div>
<script src='{% static "js/jquery.js" %}'></script>
<script src='{% static "editor/lib/marked.min.js" %}'></script>
<script src='{% static "editor/lib/prettify.min.js" %}'></script>
<script src='{% static "editor/lib/raphael.min.js" %}'></script>
<script src='{% static "editor/lib/underscore.min.js" %}'></script>
<script src='{% static "editor/lib/sequence-diagram.min.js" %}'></script>
<script src='{% static "editor/lib/flowchart.min.js" %}''></script>
<script src='{% static "editor/lib/jquery.flowchart.min.js" %}'></script>
<script src='{% static "editor/editormd.js" %}'></script>
<script type="text/javascript" src="{% static 'js/layer.js'%}"></script>
<script type="text/javascript">
$(function(){
    editormd.markdownToHTML("editormd-view", {
        htmlDecode      : "style,script,iframe",  // you can filter tags decode
        emoji           : true,
        taskList        : true,
        tex             : true,  // 預設不解析
        flowChart       : true,  // 預設不解析
        sequenceDiagram : true,  // 預設不解析
    });
});
function like_article(id,action){
    $.ajax({
        url: "{% url 'article:like_article' %}",
        type: "POST",
        data: {"id":id, "action":action},
        success: function(e){
            if(e=="1"){
                layer.msg("感謝點贊");
                window.location.reload();
            }else{
                layer.msg("我會繼續努力");
                window.location.reload();
            }
        },
    });
}
</script>
{% endwith %}
{% endblock %}

四 測試