更改富文本中的图片表示

图片在富文本中的 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 的 rendition.img_tag(extra_attributes)
                        # 来生成 HTML 表示的

        return custom_html


register_image_format(
    SubclassedImageFormat('subclassed_format', '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", "Full width captioned", "bodytext-image", "width-750"
    )
)

备注

任何自定义的 HTML 图片特性都不会在 Draftail 编辑器中显示,只在已发布的页面上显示。