neighbors.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # -*- coding: utf-8 -*-
  2. """
  3. Neighbor Articles Plugin for Pelican
  4. ====================================
  5. This plugin adds ``next_article`` (newer) and ``prev_article`` (older)
  6. variables to the article's context
  7. """
  8. from pelican import signals
  9. def iter3(seq):
  10. """Generate one triplet per element in 'seq' following PEP-479."""
  11. nxt, cur = None, None
  12. for prv in seq:
  13. if cur:
  14. yield nxt, cur, prv
  15. nxt, cur = cur, prv
  16. # Don't yield anything if empty seq
  17. if cur:
  18. # Yield last element in seq (also if len(seq) == 1)
  19. yield nxt, cur, None
  20. def get_translation(article, prefered_language):
  21. if not article:
  22. return None
  23. for translation in article.translations:
  24. if translation.lang == prefered_language:
  25. return translation
  26. return article
  27. def set_neighbors(articles, next_name, prev_name):
  28. for nxt, cur, prv in iter3(articles):
  29. setattr(cur, next_name, nxt)
  30. setattr(cur, prev_name, prv)
  31. for translation in cur.translations:
  32. setattr(translation, next_name, get_translation(nxt, translation.lang))
  33. setattr(translation, prev_name, get_translation(prv, translation.lang))
  34. def neighbors(generator):
  35. set_neighbors(generator.articles, "next_article", "prev_article")
  36. for category, articles in generator.categories:
  37. articles.sort(key=lambda x: x.date, reverse=True)
  38. set_neighbors(articles, "next_article_in_category", "prev_article_in_category")
  39. if hasattr(generator, "subcategories"):
  40. for subcategory, articles in generator.subcategories:
  41. articles.sort(key=lambda x: x.date, reverse=True)
  42. index = subcategory.name.count("/")
  43. next_name = "next_article_in_subcategory{}".format(index)
  44. prev_name = "prev_article_in_subcategory{}".format(index)
  45. set_neighbors(articles, next_name, prev_name)
  46. def register():
  47. signals.article_generator_finalized.connect(neighbors)