better_figures_and_images.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 os
  10. from pelican import signals
  11. from bs4 import BeautifulSoup
  12. from PIL import Image
  13. def content_object_init(instance):
  14. if instance._content is not None:
  15. content = instance._content
  16. soup = BeautifulSoup(content)
  17. # if '<object type="image/svg+xml"' in content:
  18. # for obj in soup('object'):
  19. # extra_style = 'max-width: 100%;'
  20. # fig = obj.find_parent('div', 'figure')
  21. # if fig:
  22. # if obj.get('style'):
  23. # obj['style'] += extra_style
  24. # else:
  25. # obj['style'] = extra_style
  26. if 'img' in content:
  27. for img in soup('img'):
  28. if instance.settings['RESPONSIVE_IMAGES']:
  29. extra_style = 'max-width: 100%;'
  30. else:
  31. # TODO: Pretty sure this isn't the right way to do this, too hard coded.
  32. # There must be a setting that I should be using?
  33. src = instance.settings['PATH'] + '/images/' + os.path.split(img['src'])[1]
  34. im = Image.open(src)
  35. extra_style = 'width: {}px; height: auto;'.format(im.size[0])
  36. if img.get('style'):
  37. img['style'] += extra_style
  38. else:
  39. img['style'] = extra_style
  40. fig = img.find_parent('div', 'figure')
  41. if fig:
  42. if fig.get('style'):
  43. fig['style'] += extra_style
  44. else:
  45. fig['style'] = extra_style
  46. instance._content = soup.decode()
  47. def register():
  48. signals.content_object_init.connect(content_object_init)