Skip to content
This repository has been archived by the owner on Jan 22, 2021. It is now read-only.

RelatedPosts templatetag. #41

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 41 additions & 1 deletion basic/blog/templatetags/blog.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
Post = models.get_model('blog', 'post')
Category = models.get_model('blog', 'category')
BlogRoll = models.get_model('blog', 'blogroll')
TaggedItem = models.get_model('tagging', 'taggeditem')

register = template.Library()

Expand Down Expand Up @@ -137,4 +138,43 @@ def get_blogroll(parser, token):
if not m:
raise template.TemplateSyntaxError, "%s tag had invalid arguments" % tag_name
var_name = m.groups()[0]
return BlogRolls(var_name)
return BlogRolls(var_name)


class RelatedPosts(template.Node):
def __init__(self, post, var_name="related_posts"):
self.post = template.Variable(post)
self.var_name = var_name

def render(self, context):
self.post = self.post.resolve(context)
rel_posts = TaggedItem.objects.get_related(self.post, Post)
context[self.var_name] = rel_posts
return ''


@register.tag()
def get_related_posts(parser, token):
"""
Returns a queryset with all related posts that share at least
one tag with this post, ordered by major coincidence.

Syntax::

{% get_related_posts post_instance as related_posts %}

"""

bits = token.split_contents()
tag_name, bits = bits[0], bits[1:]

if (len(bits) == 3) and (bits[1] != 'as'):
# variable name passed
return RelatedPosts(bits[0], bits[2])
elif len(bits) == 1:
# default var name will be used
return RelatedPosts(bits[0])
else:
raise template.TemplateSyntaxError(
'get_related_posts usage is {%% get_related_posts post_object as related_posts %%}')
get_related_posts.is_safe = True