Django學(xué)習(xí)(六)

歡迎關(guān)注我的公眾號(hào):zx94_11

創(chuàng)建自定義模版標(biāo)簽

  • simple_tag 處理數(shù)據(jù)并返回一個(gè)字符串
  • inclusion_tag 處理數(shù)據(jù)并返回所顯示的模版

每個(gè)模版標(biāo)簽?zāi)K都需要定義一個(gè)register變量作為有效的標(biāo)簽庫(kù)。

blog/templatetags/blog_tags.py

from django import template
from ..models import Post
from django.db.models import Count
from django.utils.safestring import mark_safe
import markdown

register = template.Library()


@register.simple_tag #注冊(cè)為簡(jiǎn)單的標(biāo)簽
def total_posts():
    return Post.published.count()


@register.inclusion_tag('blog/post/latest_posts.html')
def show_latest_posts(count=5):
    latest_posts = Post.published.order_by('-publish')[:count]
    return {'latest_posts': latest_posts}


@register.simple_tag
def get_most_commented_posts(count=5):
    return Post.published.annotate(
        total_comments=Count('comments')
    ).order_by('-total_comments')[:count]


@register.filter(name='markdown')
def markdown_format(text):
    return mark_safe(markdown.markdown(text))

blog/post/latest_posts.html

<ul>
    {% for post in latest_posts %}
        <li>
            <a href="{{ post.get_absolute_url }}">{{ post.title }}</a>
        </li>
    {% endfor %}
</ul>

使用標(biāo)簽

  • 在html文件上使用total_posts
{% load blog_tags %}
<p>This is my blog. I`ve written {% total_posts %} posts so far.</p>
效果
  • 在html文件上使用show_latest_posts
<h3>Latest posts</h3>
{% show_latest_posts 3 %}
效果
  • 在html文件上使用get_most_commented_posts
<h3>Most commented posts</h3>
{% get_most_commented_posts as most_commented_posts %}
<ul>
    {% for post in most_commented_posts %}
        <li>
            <a href="{{ post.get_absolute_url }}">{{ post.title }}</a>
        </li>
    {% endfor %}
</ul>
效果

整體

整體

創(chuàng)建自定義模版過濾器

$ pip install Markdown==2.6.11

在博客內(nèi)使用Markdown語法

@register.filter(name='markdown')
def markdown_format(text):
    return mark_safe(markdown.markdown(text))
{{ post.body|truncatewords:30|linebreaks }}
替換為
{{ post.body|markdown|truncatewords_html:30 }}

{{ post.body|linebreaks }}
替換為
{{ post.body|markdown }}
添加博客
image-20190530234625918
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容