This repository has been archived on 2023-05-31. You can view files and clone it, but cannot push or open issues or pull requests.
python-blog/src/articles/markdown.py

38 lines
1.1 KiB
Python
Raw Normal View History

2020-08-25 23:06:12 +02:00
from markdown import Markdown
from markdown.extensions import Extension
from markdown.inlinepatterns import (
IMAGE_LINK_RE,
IMAGE_REFERENCE_RE,
ImageInlineProcessor,
ImageReferenceInlineProcessor,
)
class LazyImageInlineProcessor(ImageInlineProcessor):
def handleMatch(self, m, data):
el, match_start, index = super().handleMatch(m, data)
if el is not None:
el.set("loading", "lazy")
2020-08-25 23:06:12 +02:00
return el, match_start, index
class LazyImageReferenceInlineProcessor(ImageReferenceInlineProcessor):
def makeTag(self, href, title, text):
el = super().makeTag(href, title, text)
if el is not None:
el.set("loading", "lazy")
2020-08-25 23:06:12 +02:00
return el
class LazyLoadingImageExtension(Extension):
def extendMarkdown(self, md: Markdown):
md.inlinePatterns.register(
LazyImageInlineProcessor(IMAGE_LINK_RE, md), "image_link", 150
)
md.inlinePatterns.register(
LazyImageReferenceInlineProcessor(IMAGE_REFERENCE_RE, md),
"image_reference",
140,
)
md.registerExtension(self)