Django学习(六)

2019-05-30  本文已影响0人  测试游记

欢迎关注我的公众号:zx94_11

创建自定义模版标签

每个模版标签模块都需要定义一个register变量作为有效的标签库。

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 #注册为简单的标签
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>

使用标签

{% load blog_tags %}
<p>This is my blog. I`ve written {% total_posts %} posts so far.</p>
效果
<h3>Latest posts</h3>
{% show_latest_posts 3 %}
效果
<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>
效果

整体

整体

创建自定义模版过滤器

$ pip install Markdown==2.6.11

在博客内使用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
上一篇下一篇

猜你喜欢

热点阅读