better_figures_and_images.py 1.6 KB

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