summary.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. """
  2. Summary
  3. -------
  4. This plugin allows easy, variable length summaries directly embedded into the
  5. body of your articles.
  6. """
  7. from __future__ import unicode_literals
  8. from pelican import signals
  9. from pelican.generators import ArticlesGenerator, StaticGenerator, PagesGenerator
  10. def initialized(pelican):
  11. from pelican.settings import DEFAULT_CONFIG
  12. DEFAULT_CONFIG.setdefault('SUMMARY_BEGIN_MARKER',
  13. '<!-- PELICAN_BEGIN_SUMMARY -->')
  14. DEFAULT_CONFIG.setdefault('SUMMARY_END_MARKER',
  15. '<!-- PELICAN_END_SUMMARY -->')
  16. if pelican:
  17. pelican.settings.setdefault('SUMMARY_BEGIN_MARKER',
  18. '<!-- PELICAN_BEGIN_SUMMARY -->')
  19. pelican.settings.setdefault('SUMMARY_END_MARKER',
  20. '<!-- PELICAN_END_SUMMARY -->')
  21. def extract_summary(instance):
  22. # if summary is already specified, use it
  23. # if there is no content, there's nothing to do
  24. if hasattr(instance, '_summary'):
  25. instance.has_summary = True
  26. return
  27. if not instance._content:
  28. instance.has_summary = False
  29. return
  30. begin_marker = instance.settings['SUMMARY_BEGIN_MARKER']
  31. end_marker = instance.settings['SUMMARY_END_MARKER']
  32. content = instance._content
  33. begin_summary = -1
  34. end_summary = -1
  35. if begin_marker:
  36. begin_summary = content.find(begin_marker)
  37. if end_marker:
  38. end_summary = content.find(end_marker)
  39. if begin_summary == -1 and end_summary == -1:
  40. instance.has_summary = False
  41. return
  42. # skip over the begin marker, if present
  43. if begin_summary == -1:
  44. begin_summary = 0
  45. else:
  46. begin_summary = begin_summary + len(begin_marker)
  47. if end_summary == -1:
  48. end_summary = None
  49. summary = content[begin_summary:end_summary]
  50. # remove the markers from the content
  51. if begin_summary:
  52. content = content.replace(begin_marker, '', 1)
  53. if end_summary:
  54. content = content.replace(end_marker, '', 1)
  55. instance._content = content
  56. instance._summary = summary
  57. instance.has_summary = True
  58. def run_plugin(generators):
  59. for generator in generators:
  60. if isinstance(generator, ArticlesGenerator):
  61. for article in generator.articles:
  62. extract_summary(article)
  63. elif isinstance(generator, PagesGenerator):
  64. for page in generator.pages:
  65. extract_summary(page)
  66. def register():
  67. signals.initialized.connect(initialized)
  68. try:
  69. signals.all_generators_finalized.connect(run_plugin)
  70. except AttributeError:
  71. # NOTE: This results in #314 so shouldn't really be relied on
  72. # https://github.com/getpelican/pelican-plugins/issues/314
  73. signals.content_object_init.connect(extract_summary)