better_figures_and_images.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. """
  2. Better Figures & Images
  3. ------------------------
  4. This plugin:
  5. - Adds a style="width: ???px; height: auto;" to each image in the content
  6. - Also adds the width of the contained image to any parent div.figures.
  7. - If RESPONSIVE_IMAGES == True, also adds style="max-width: 100%;"
  8. - Corrects alt text: if alt == image filename, set alt = ''
  9. TODO: Need to add a test.py for this plugin.
  10. """
  11. import os
  12. from pelican import signals
  13. from bs4 import BeautifulSoup
  14. from PIL import Image
  15. def content_object_init(instance):
  16. if instance._content is not None:
  17. content = instance._content
  18. soup = BeautifulSoup(content)
  19. if 'img' in content:
  20. for img in soup('img'):
  21. # TODO: Pretty sure this isn't the right way to do this, too hard coded.
  22. # There must be a setting that I should be using?
  23. src = instance.settings['PATH'] + '/images/' + os.path.split(img['src'])[1]
  24. im = Image.open(src)
  25. extra_style = 'width: {}px; height: auto;'.format(im.size[0])
  26. if instance.settings['RESPONSIVE_IMAGES']:
  27. extra_style += ' max-width: 100%;'
  28. if img.get('style'):
  29. img['style'] += extra_style
  30. else:
  31. img['style'] = extra_style
  32. if img['alt'] == img['src']:
  33. img['alt'] = ''
  34. fig = img.find_parent('div', 'figure')
  35. if fig:
  36. if fig.get('style'):
  37. fig['style'] += extra_style
  38. else:
  39. fig['style'] = extra_style
  40. instance._content = soup.decode()
  41. def register():
  42. signals.content_object_init.connect(content_object_init)