sub_parts.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. from pelican import signals
  4. import logging
  5. logger = logging.getLogger(__name__)
  6. def patch_subparts(generator):
  7. generator.subparts = []
  8. slugs = {}
  9. for article in generator.articles:
  10. slugs[article.slug] = article
  11. if '--' in article.slug:
  12. generator.subparts.append(article)
  13. for article in generator.subparts:
  14. logger.info('sub_part: Detected %s', article.slug)
  15. (pslug, _) = article.slug.rsplit('--', 1)
  16. if pslug in slugs:
  17. parent = slugs[pslug]
  18. if not hasattr(parent, 'subparts'):
  19. parent.subparts = []
  20. parent.subparts.append(article)
  21. article.subpart_of = parent
  22. article.subtitle = article.title
  23. article.title = article.title + ", " + parent.title
  24. generator.dates.remove(article)
  25. generator.articles.remove(article)
  26. if article.category:
  27. for cat, arts in generator.categories:
  28. if cat.name == article.category.name:
  29. arts.remove(article)
  30. break
  31. else:
  32. logger.error(
  33. 'sub_part: Cannot remove sub-part from category %s',
  34. article.category)
  35. if (hasattr(article, 'subphotos') or
  36. hasattr(article, 'photo_gallery')):
  37. parent.subphotos = (
  38. getattr(parent, 'subphotos',
  39. len(getattr(parent, 'photo_gallery', []))) +
  40. getattr(article, 'subphotos', 0) +
  41. len(getattr(article, 'photo_gallery', [])))
  42. else:
  43. logger.error('sub_part: No parent for %s', pslug)
  44. generator._update_context(('articles', 'dates', 'subparts'))
  45. def write_subparts(generator, writer):
  46. for article in generator.subparts:
  47. signals.article_generator_write_article.send(generator,
  48. content=article)
  49. writer.write_file(
  50. article.save_as, generator.get_template(article.template),
  51. generator.context, article=article, category=article.category,
  52. override_output=hasattr(article, 'override_save_as'),
  53. relative_urls=generator.settings['RELATIVE_URLS'])
  54. if len(generator.subparts) > 0:
  55. print('sub_part: processed {} sub-parts.'.format(
  56. len(generator.subparts)))
  57. def register():
  58. signals.article_generator_finalized.connect(patch_subparts)
  59. signals.article_writer_finalized.connect(write_subparts)