changing_rich_text_representation.rst 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. .. _changing_rich_text_representation:
  2. =================================
  3. Changing rich text representation
  4. =================================
  5. The HTML representation of an image in rich text can be customised - for example, to display captions or custom fields.
  6. To do this requires subclassing ``Format`` (see :ref:`rich_text_image_formats`), and overriding its ``image_to_html`` method.
  7. You may then register formats of your subclass using ``register_image_format`` as usual.
  8. .. code-block:: python
  9. # image_formats.py
  10. from wagtail.images.formats import Format, register_image_format
  11. class SubclassedImageFormat(Format):
  12. def image_to_html(self, image, alt_text, extra_attributes=None):
  13. custom_html = # the custom HTML representation of your image here
  14. # in Format, the image's rendition.img_tag(extra_attributes) is used to generate the HTML
  15. # representation
  16. return custom_html
  17. register_image_format(
  18. SubclassedImageFormat('subclassed_format', 'Subclassed Format', classnames, filter_spec)
  19. )
  20. As an example, let's say you want the alt text to be displayed as a caption for the image as well:
  21. .. code-block:: python
  22. # image_formats.py
  23. from django.utils.html import format_html
  24. from wagtail.images.formats import Format, register_image_format
  25. class CaptionedImageFormat(Format):
  26. def image_to_html(self, image, alt_text, extra_attributes=None):
  27. default_html = super().image_to_html(image, alt_text, extra_attributes)
  28. return format_html("{}<figcaption>{}</figcaption>", default_html, alt_text)
  29. register_image_format(
  30. CaptionedImageFormat('captioned_fullwidth', 'Full width captioned', 'bodytext-image', 'width-750')
  31. )
  32. .. note::
  33. Any custom HTML image features will not be displayed in the Draftail editor, only on the published page.