I initially thought that how to pass class attribute and value to markdown syntax and How do I set an HTML class attribute in Markdown? asked the question that I want to ask here, but I want to know how to write an python-markdown extension that outputs an html span element with specific class attribute in Django.
I've written the following extension (file saved as "mdx_debatesyntax.py"):
import markdown
from markdown.inlinepatterns import Pattern
PREMISE_RE = r'(\[p )(.*?)\]'
class AttrTagPattern(Pattern):
"""
Return element of type `tag` with a text attribute of group(3)
of a Pattern and with the html attributes defined with the constructor.
"""
def __init__ (self, pattern, tag, attrs):
Pattern.__init__(self, pattern)
self.tag = tag
self.attrs = attrs
def handleMatch(self, m):
el = markdown.util.etree.Element(self.tag)
el.text = m.group(3)
for (key,val) in self.attrs.items():
el.set(key,val)
return el
class DebateSyntaxExtension(markdown.Extension):
def extendMarkdown(self, md, md_globals):
premise_tag = AttrTagPattern(PREMISE_RE, 'span',{'class':'premise'})
md.inlinePatterns.add('premise', premise_tag, '_begin')
def makeExtension(configs=None):
return DebateSyntaxExtension(configs=configs)
And when I test this directly (not through Django) it works:
import markdown
md = markdown.Markdown(extensions=['debatesyntax'])
md.convert('This is a [p test]!')
Returns
u'<p>This is a <span class="premise">test</span>!</p>'
However, when I run this through Django, the attribute class gets stripped, giving me:
<p>This is a <span>test</span>!</p>
How do I prevent the class attribute (or other attributes) from being stripped?
Resolution
The Django app that I was modifying (OSQA), was manually "sanitizing" the HTML. The AttrTagPattern class code does, after all, work.