3

I am trying to make it so that when a body image is inserted into a page, that the bootstap class "img-responsive" is added to the image tag?

Can anyone tell me how to achieve this?

amphetamachine
  • 27,620
  • 12
  • 60
  • 72
Chris Barry
  • 4,564
  • 7
  • 54
  • 89
  • 1
    Please improve your question with more information: What have you tried [post code]? What exactly are you trying to accomplish. – amphetamachine Feb 26 '15 at 17:58

1 Answers1

10

You can do this through image formats:

http://docs.wagtail.io/en/v0.8.5/core_components/pages/editing_api.html#image-formats-in-the-rich-text-editor

The "Full width" / "Left-aligned" / "Right-aligned" options you usually get when inserting an image into the rich text area come from Format objects, which determine how to translate the image reference into the final tag. So, you need to replace the built-in Format objects with ones that insert your classname. Create a file 'image_formats.py' within your app, containing the following:

from wagtail.wagtailimages.formats import Format, register_image_format, unregister_image_format

unregister_image_format('fullwidth')
register_image_format(Format('fullwidth', 'Full width', 'richtext-image full-width img-responsive', 'width-800'))

unregister_image_format('left')
register_image_format(Format('left', 'Left-aligned', 'richtext-image left img-responsive', 'width-500'))

unregister_image_format('right')
register_image_format(Format('right', 'Right-aligned', 'richtext-image right img-responsive', 'width-500'))
gasman
  • 23,691
  • 1
  • 38
  • 56
  • Great answer, this answer helped run the code at app start - http://stackoverflow.com/a/16111968/6822 – Chris Barry Apr 13 '15 at 20:35
  • Glad you got it to work! You shouldn't have to do anything special to run the code at startup, though - the wagtailimages app will specifically look for an 'image_formats' module within all apps. – gasman Apr 14 '15 at 21:46
  • Hey gasman, this answer doesn't seem to be good, since as I tested that the images inserted in `RichTextField` are all generated with `height` and `width` attributes, such as `ring1.jpeg` could you please tell me how to remove the `height` and `width` attributes? – avocado Jun 29 '20 at 23:35
  • Found a solution, monkey-patch `Rendition.img_tag`, https://docs.wagtail.io/en/stable/advanced_topics/amp.html?highlight=img_tag#overriding-the-image-tag-to-output-amp-img-tags – avocado Jun 30 '20 at 00:14