我最初认为how to pass class attribute and value to markdown syntax和How do I set an HTML class attribute in Markdown?提出了我想问的问题,但我想知道如何编写输出的python-markdown 扩展 Django中具有特定类属性的html span元素。
我写了以下扩展名(文件保存为“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)
当我直接测试它(而不是通过Django)时,它可以工作:
import markdown
md = markdown.Markdown(extensions=['debatesyntax'])
md.convert('This is a [p test]!')
返回
u'<p>This is a <span class="premise">test</span>!</p>'
但是,当我通过Django运行时,属性类被剥离,给我:
<p>This is a <span>test</span>!</p>
如何防止类属性(或其他属性)被剥离?
解决
我正在修改的Django应用程序(OSQA)是手动“清理”HTML。毕竟,AttrTagPattern类代码可以正常工作。
答案 0 :(得分:3)
试
{{ value|markdown:"debatesyntax" }}