neighbors.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. it = iter(seq)
  11. nxt = None
  12. cur = next(it)
  13. for prv in it:
  14. yield nxt, cur, prv
  15. nxt, cur = cur, prv
  16. yield nxt, cur, None
  17. def get_translation(article, prefered_language):
  18. if not article:
  19. return None
  20. for translation in article.translations:
  21. if translation.lang == prefered_language:
  22. return translation
  23. return article
  24. def set_neighbors(articles, next_name, prev_name):
  25. for nxt, cur, prv in iter3(articles):
  26. exec("cur.{} = nxt".format(next_name))
  27. exec("cur.{} = prv".format(prev_name))
  28. for translation in cur.translations:
  29. exec("translation.{} = get_translation(nxt, translation.lang)".format(next_name))
  30. exec("translation.{} = get_translation(prv, translation.lang)".format(prev_name))
  31. def neighbors(generator):
  32. set_neighbors(generator.articles, 'next_article', 'prev_article')
  33. for category, articles in generator.categories:
  34. articles.sort(key=(lambda x: x.date), reverse=(True))
  35. set_neighbors(
  36. articles, 'next_article_in_category', 'prev_article_in_category')
  37. if hasattr(generator, 'subcategories'):
  38. for subcategory, articles in generator.subcategories:
  39. articles.sort(key=(lambda x: x.date), reverse=(True))
  40. index = subcategory.name.count('/')
  41. next_name = 'next_article_in_subcategory{}'.format(index)
  42. prev_name = 'prev_article_in_subcategory{}'.format(index)
  43. set_neighbors(articles, next_name, prev_name)
  44. def register():
  45. signals.article_generator_finalized.connect(neighbors)