related_posts.py 895 B

1234567891011121314151617181920212223242526272829303132333435
  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. # no tag, no relation
  14. if not hasattr(article, 'tags'):
  15. continue
  16. # score = number of common tags
  17. scores = Counter()
  18. for tag in article.tags:
  19. scores += Counter(generator.tags[tag])
  20. # remove itself
  21. scores.pop(article)
  22. article.related_posts = [other for other, count
  23. in scores.most_common(numentries)]
  24. def register():
  25. signals.article_generator_finalized.connect(add_related_posts)