neighbors.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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(
  30. "translation.{} = get_translation(nxt, translation.lang)".format(
  31. next_name))
  32. exec(
  33. "translation.{} = get_translation(prv, translation.lang)".format(
  34. prev_name))
  35. def neighbors(generator):
  36. set_neighbors(generator.articles, 'next_article', 'prev_article')
  37. for category, articles in generator.categories:
  38. articles.sort(key=(lambda x: x.date), reverse=(True))
  39. set_neighbors(
  40. articles, 'next_article_in_category', 'prev_article_in_category')
  41. if hasattr(generator, 'subcategories'):
  42. for subcategory, articles in generator.subcategories:
  43. articles.sort(key=(lambda x: x.date), reverse=(True))
  44. index = subcategory.name.count('/')
  45. next_name = 'next_article_in_subcategory{}'.format(index)
  46. prev_name = 'prev_article_in_subcategory{}'.format(index)
  47. set_neighbors(articles, next_name, prev_name)
  48. def register():
  49. signals.article_generator_finalized.connect(neighbors)