related_posts.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. """
  2. Related posts plugin for Pelican
  3. ================================
  4. Adds related_posts variable to article's context
  5. """
  6. from pelican import signals
  7. from collections import Counter
  8. def add_related_posts(generator):
  9. # get the max number of entries from settings
  10. # or fall back to default (5)
  11. numentries = generator.settings.get('RELATED_POSTS_MAX', 5)
  12. for article in generator.articles:
  13. # set priority in case of forced related posts
  14. if hasattr(article,'related_posts'):
  15. # split slugs
  16. related_posts = article.related_posts.split(',')
  17. posts = []
  18. # get related articles
  19. for slug in related_posts:
  20. i = 0
  21. for a in generator.articles:
  22. if i >= numentries: # break in case there are max related psots
  23. break
  24. if a.slug == slug:
  25. posts.append(a)
  26. i += 1
  27. article.related_posts = posts
  28. else:
  29. # no tag, no relation
  30. if not hasattr(article, 'tags'):
  31. continue
  32. # score = number of common tags
  33. scores = Counter()
  34. for tag in article.tags:
  35. scores += Counter(generator.tags[tag])
  36. # remove itself
  37. scores.pop(article)
  38. article.related_posts = [other for other, count
  39. in scores.most_common(numentries)]
  40. def register():
  41. signals.article_generator_finalized.connect(add_related_posts)