Django ブログサイト templatetags テンプレートタグ

2020/07/04 (更新:2020/11/19)

テンプレートタグです。

カテゴリービュータグ

サイドバーのカテゴリ一覧を表示するテンプレートタグです。
出力テンプレートにcategory_summary.htmlを指定します。

category_summary

register = template.Library()

@register.inclusion_tag('blog/category_summary.html', takes_context=True)
def category_summary(context, author_id):
    posts = models.Post.objects.filter(
                author=author_id,
                status__gte=models.PostStatus.PUBLIC,
                postcontent__language_code=context.request.LANGUAGE_CODE,
            )
    return {
        "categories": models.PostCategory.objects.values('category__id', 'category__category_text')
            .filter(post__in=posts).annotate(Count('post')),
    }

templates/category_summary.html

{% load i18n %}
<h4 class="font-italic">{% trans 'Category' %}</h4>
<div>
    {% for category in categories %}
        <a href="#" data-category-text="{{ category.category__category_text }}" class="category badge badge-light"><span>{{ category.category__category_text }}</span> (<span>{{ category.post__count }}</span>)</a>
    {% endfor %}
</div>

おすすめブログビュータグ

サイドバーのおすすめブログを表示するテンプレートタグです。
出力テンプレートにblog_favor.htmlを指定します。

post_favor

@register.inclusion_tag('blog/post_favor.html', takes_context=True)
def post_favor(context, author_id, count):
    return {
        "favor_posts": models.PostContent.objects.filter(
                post__author=author_id,
                language_code=context.request.LANGUAGE_CODE,
                post__status__gte=models.PostStatus.PUBLIC
            ).order_by('-post__view_count')[:count]
    }

templates/post_favor.html

{% load i18n %}
<h4 class="font-italic">{% trans 'Favor' %}</h4>
<ul class="list-group list-group-flush">
    {% for post_content in favor_posts %}
        <li class="list-group-item">
            <a class="favor-title" href="{% url 'blog:detail' post_content.post.author.user.username post_content.post.id %}">{{ post_content.title_text }}</a>
        </li>
    {% endfor %}
</ul>