better_figures_and_images.py 2.2 KB

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