Skip to content

Tutorial

flywire edited this page Jan 29, 2023 · 3 revisions

Tutorial 2 Altering Markdown Rendering

Lets use files:

ImageExtension.py

from markdown.treeprocessors import Treeprocessor
from markdown.extensions import Extension


class InlineImageProcessor(Treeprocessor):
    def run(self, root):
        # Modify the HTML here
        print("Hello world")


class ImageExtension(Extension):
    def __init__(self, **kwargs):
        self.config = {'hosts' : [[], 'List of approved hosts']}
        super(ImageExtension, self).__init__(**kwargs)

    def extendMarkdown(self, md):
        md.treeprocessors.register(InlineImageProcessor(md), 'inlineimageprocessor', 15)

input.md

![a local image](/path/to/image.jpg "A title.")

![a remote image](http://example.com/image.jpg  "A title.")

test.py

import markdown
import sys
with open("input.md", "r", encoding="utf-8") as input_file:
    input = input_file.read()

from ImageExtension import ImageExtension
html = markdown.markdown(input, extensions=[ImageExtension()])
print(html)

Run with python test.py > test.html

Open html file in browser and text editor. The browser will use an image placeholder and display the alt text. Hover the mouse over the image to display the title or copy the image address.

Clone this wiki locally