diff options
author | Botond Hende <nettingman@gmail.com> | 2024-07-15 23:35:02 +0200 |
---|---|---|
committer | Botond Hende <nettingman@gmail.com> | 2024-07-15 23:59:14 +0200 |
commit | d0a873b8be0d6dd19f1c424782789b27a3649c45 (patch) | |
tree | 4577bfbf01723ca61f176e375f6305c1f23968fa /extendedimage.py | |
parent | 3295abdee147801c86b56ec77643dcc416f8ed3e (diff) |
extended image module
Diffstat (limited to 'extendedimage.py')
-rw-r--r-- | extendedimage.py | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/extendedimage.py b/extendedimage.py new file mode 100644 index 0000000..b62f100 --- /dev/null +++ b/extendedimage.py @@ -0,0 +1,40 @@ +from marko import inline +from marko.helpers import MarkoExtension + + +class ExtendedImage(inline.InlineElement): + pattern = r'!\[(.*)\]\(((?:[^"\s\\]|\\.)+|"(?:[^"\\]|\\.)*")\s((?:[^"\s\\]|\\.)+|"(?:[^"\\]|\\.)*")\s((?:[^"\s\\]|\\.)+|"(?:[^"\\]|\\.)*")\s((?:[^"\s\\]|\\.)+|"(?:[^"\\]|\\.)*")\)' + parse_children = True + + def __init__(self, match): + self.alt = self.__strip_quotes(match.group(1)) + self.src = self.__strip_quotes(match.group(2)) + self.title = self.__strip_quotes(match.group(3)) + self.href = self.__strip_quotes(match.group(4)) + self.figcaption = self.__strip_quotes(match.group(5)) + + @staticmethod + def __strip_quotes(text: str) -> str: + if text.startswith('"'): + return text[1:-1] + + return text + + +class ExtendedImageRenderer: + def render_extended_image(self, element): + img = f'<img src="{element.src}" title="{element.title}" alt="{element.alt}" />' + + if element.href != "": + img = f'<a href="{element.href}">{img}</a>' + + if element.figcaption != "": + img = f"<figure>{img}<figcaption>{element.figcaption}</figcaption></figure>" + + return img + + +ExtendedImage = MarkoExtension( + elements=[ExtendedImage], + renderer_mixins=[ExtendedImageRenderer] +) |