clean_summary.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. """
  2. Clean Summary
  3. -------------
  4. adds option to specify maximum number of images to appear in article summary
  5. also adds option to include an image by default if one exists in your article
  6. """
  7. from pelican import signals
  8. from pelican.contents import Content, Article
  9. from bs4 import BeautifulSoup
  10. from six import text_type
  11. def clean_summary(instance):
  12. if "CLEAN_SUMMARY_MAXIMUM" in instance.settings:
  13. maximum_images = instance.settings["CLEAN_SUMMARY_MAXIMUM"]
  14. else:
  15. maximum_images = 0
  16. if "CLEAN_SUMMARY_MINIMUM_ONE" in instance.settings:
  17. minimum_one = instance.settings['CLEAN_SUMMARY_MINIMUM_ONE']
  18. else:
  19. minimum_one = False
  20. if type(instance) == Article:
  21. summary = instance.summary
  22. summary = BeautifulSoup(instance.summary, 'html.parser')
  23. images = summary.findAll('img')
  24. if (len(images) > maximum_images):
  25. for image in images[maximum_images:]:
  26. image.extract()
  27. if len(images) < 1 and minimum_one: #try to find one
  28. content = BeautifulSoup(instance.content, 'html.parser')
  29. first_image = content.find('img')
  30. if first_image:
  31. summary.insert(0, first_image)
  32. instance._summary = text_type(summary)
  33. def register():
  34. signals.content_object_init.connect(clean_summary)