0
0
mirror of https://github.com/wagtail/wagtail.git synced 2024-11-24 10:58:52 +01:00
wagtail/docs/advanced_topics/images/changing_rich_text_representation.md
Buraah 56335de636 Update documentation globally to use US spelling (not UK) + grammar fixes
- Transferred all British spellings in the usage guide and advanced topics section to American spellings
2024-01-30 07:30:57 +10:00

1.7 KiB

(changing_rich_text_representation)=

Changing rich text representation

The HTML representation of an image in rich text can be customized - for example, to display captions or custom fields.

To do this requires subclassing Format (see ), and overriding its image_to_html method.

You may then register formats of your subclass using register_image_format as usual.

# image_formats.py
from wagtail.images.formats import Format, register_image_format


class SubclassedImageFormat(Format):

    def image_to_html(self, image, alt_text, extra_attributes=None):

        custom_html = # the custom HTML representation of your image here
                        # in Format, the image's rendition.img_tag(extra_attributes) is used to generate the HTML
                        # representation

        return custom_html


register_image_format(
    SubclassedImageFormat('subclassed_format', 'Subclassed Format', 'image-classes object-contain', filter_spec)
)

As an example, let's say you want the alt text to be displayed as a caption for the image as well:

# image_formats.py
from django.utils.html import format_html
from wagtail.images.formats import Format, register_image_format


class CaptionedImageFormat(Format):

    def image_to_html(self, image, alt_text, extra_attributes=None):

        default_html = super().image_to_html(image, alt_text, extra_attributes)

        return format_html("{}<figcaption>{}</figcaption>", default_html, alt_text)


register_image_format(
    CaptionedImageFormat('captioned_fullwidth', 'Full width captioned', 'bodytext-image', 'width-750')
)
Any custom HTML image features will not be displayed in the Draftail editor, only on the published page.