리치 텍스트 표현 변경

리치 텍스트에서 이미지의 HTML 표현은 캡션이나 사용자 지정 필드를 표시하는 등 사용자 지정할 수 있습니다.

이를 위해서는 Format 을 서브클래싱하고( 서식 있는 텍스트 편집기의 이미지 형식 참조) image_to_html 메서드를 재정의해야 합니다.

그런 다음 평소와 같이 register_image_format 을 사용하여 서브클래스의 형식을 등록할 수 있습니다.

# 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 = # 여기에 이미지의 사용자 지정 HTML 표현
                        # Format에서 이미지의 rendition.img_tag(extra_attributes)는 HTML
                        # 표현을 생성하는 데 사용됩니다.

        return custom_html


register_image_format(
    SubclassedImageFormat('subclassed_format', '서브클래스 형식', 'image-classes object-contain', filter_spec)
)

예를 들어, 대체 텍스트를 이미지의 캡션으로도 표시하고 싶다고 가정해 봅시다.

# 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', '캡션이 있는 전체 너비', 'bodytext-image', 'width-750')
)

참고

사용자 지정 HTML 이미지 기능은 Draftail 편집기에는 표시되지 않고 게시된 페이지에만 표시됩니다.