The Python Markdown module, perhaps outdated, but the one that I use, can be extended using plugins. Here is a plugin I needed and built. It adds a user-specified CSS class to the generated P tags. It draws heavily on the examples at the above website. (I also had to read the code.)
# the name "markdown" was taken, in my module, so I aliased it
import markdown as markdownmodule
class ClassAdderTreeprocessor(markdownmodule.treeprocessors.Treeprocessor):
"""Markdown extension for h.markdownWithCssClass()"""
def run(self, root):
self.set_css_class(root)
return root
def set_css_class(self, element):
"""Sets class attribute of P tags to configured CSS class."""
for child in element:
if child.tag == "p":
child.set("class", self.ext.getConfig("css_class") ) #set the class attribute
self.set_css_class(child) # run recursively on children
class ClassAdderExtension(markdownmodule.Extension):
"""Markdown extension for h.markdownWithCssClass()"""
def __init__(self, *args, **configs):
# define default configs
self.config = {
'css_class' : ["something-css-like",
"Set class name for p tags - Default: something-css-like"]
}
# Override defaults with user settings
for key, value in configs.items():
self.setConfig(key, value)
def extendMarkdown(self, md, md_globals):
# Insert a tree-processor that adds the configured CSS class to P tags
treeprocessor = ClassAdderTreeprocessor(md)
treeprocessor.ext = self
md.treeprocessors['css'] = treeprocessor
def markdownWithCssClass(txt, cssClass):
"""Works like markdown() but adds given CSS class on generated P tags."""
ext = ClassAdderExtension(css_class=cssClass)
md = markdownmodule.Markdown(extensions=[ext], safe_mode='escape')
html = md.convert(txt)
return html
Have you written a plugin for this thing? Any other comments? Which Markdown processor in Python should I be using if not this one?