--- title: How to extend Markdown with custom blocks date: "2021-01-08T09:37:48Z" lastmod: "2021-01-08T09:37:52Z" categories: - coding wp_id: 3059 description: I use the markdown-customblocks library to extend Python Markdown for complex layouts. This allows me to create nested Bootstrap columns and custom tags, like audio players, directly within Markdown files without writing raw HTML code. keywords: [markdown-customblocks, python-markdown, bootstrap grid, custom blocks, markdown extension, html generation] --- One problem I've had in Markdown is rendering a content in columns. On Bootstrap, the markup would look like this: ```markup   ...   ... ``` How do we get that into Markdown without writing HTML? On Python, the [attribute lists extension](https://python-markdown.github.io/extensions/attr_list/) lets you add a class. For example: ```markdown This is some content {: .row} ``` ... renders `

This is some content

`. But I can't do that to multiple paragraphs. Nor can I next content, i.e. add a `.col` inside the `.row`. Enter [markdown-customblocks](https://pypi.org/project/markdown-customblocks/). It's a Python module that extends [Python Markdown](https://python-markdown.github.io/). This lets me write: ```markdown ::: row ::: col Content in column 1 ::: col Content in column 2 ::: row ::: col Content in column 1 ::: col Content in column 2 ``` This translates to: ```markup
Content in column 1
Content in column 2
``` Better yet, we can create our own custom HTML block types. For example, this code: ```python from markdown import Markdown from customblocks import CustomBlocksExtension def audio(ctx, src, type="audio/mp3"):     return f'''       {ctx.content}     ''' md = Markdown(extensions=[     CustomBlocksExtension(generators={         'audio': audio     }), ]) ``` ... lets you convert this piece of Markdown: ```python md.convert(""" ::: audio src="mymusic.ogg" type="audio/ogg"     Your browser does not support `audio`. """) ``` ... into this HTML: ```markup   Your browser does not support audio. ``` [markdown-customblocks](https://pypi.org/project/markdown-customblocks/) is easily the most useful Python module I discovered last quarter.