Skip to content

Commit 1e41544

Browse files
committed
Add custom template tags and filters
1 parent cb291f5 commit 1e41544

File tree

5 files changed

+42
-2
lines changed

5 files changed

+42
-2
lines changed

mysite/apps/blog/templates/blog/post/detail.html

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
{% extends "base.html" %}
2+
{% load blog_tags %}
23

34
{% block title %}{{ post.title }}{% endblock %}
45

@@ -7,7 +8,7 @@ <h1>{{ post.title }}</h1>
78
<p class="date">
89
Published {{ post.publish }} by {{ post.author }}
910
</p>
10-
{{ post.body|linebreaks }}
11+
{{ post.body|markdown }}
1112
<p>
1213
<a href="{% url "blog:post_share" post.id %}">
1314
Share this post
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<ul>
2+
{% for post in latest_posts %}
3+
<li>
4+
<a href="{{ post.get_absolute_url }}">{{ post.title }}</a>
5+
</li>
6+
{% endfor %}
7+
</ul>

mysite/apps/blog/templates/blog/post/list.html

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
{% extends "base.html" %}
2+
{% load blog_tags %}
23

34
{% block title %}My Blog{% endblock %}
45

@@ -26,7 +27,7 @@ <h2>
2627
<p class="date">
2728
Published {{ post.publish }} by {{ post.author }}
2829
</p>
29-
{{ post.body|truncatewords:30|linebreaks }}
30+
{{ post.body|markdown|truncatewords_html:30 }}
3031
{% endfor %}
3132
{% include "pagination.html" with page=posts %}
3233
{% endblock %}

mysite/apps/blog/templatetags/__init__.py

Whitespace-only changes.
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
from django import template
2+
from django.db.models import Count
3+
from django.utils.safestring import mark_safe
4+
import markdown
5+
from ..models import Post
6+
7+
8+
register = template.Library()
9+
10+
11+
@register.simple_tag
12+
def total_posts():
13+
return Post.published.count()
14+
15+
16+
@register.inclusion_tag('blog/post/latest_posts.html')
17+
def show_latest_posts(count=5):
18+
latest_posts = Post.published.order_by('-publish')[:count]
19+
return {'latest_posts': latest_posts}
20+
21+
22+
@register.simple_tag
23+
def get_most_commented_posts(count=5):
24+
return Post.published.annotate(
25+
total_comments=Count('comments')
26+
).order_by('-total_comments')[:count]
27+
28+
29+
@register.filter(name='markdown')
30+
def markdown_format(text):
31+
return mark_safe(markdown.markdown(text))

0 commit comments

Comments
 (0)