我正在使用 python markdown 来执行以下操作:
当有表单的表达式时[test]
,我想将其呈现为
<span>[<a>test</a>]</span>
为此,我正在对 markdown 的 inlinePatterns 应用扩展:
PATTERN = r'\[(test)\]'
class PerceptionPattern(Pattern):
def handleMatch(self, m):
span = etree.Element('span')
anchor = etree.SubElement(span, "a")
span.text = markdown.util.AtomicString("[")
span.tail = markdown.util.AtomicString("]")
anchor.text = m.group(2)
return span
class TestExtension(markdown.extensions.Extension):
"""Adds cite extension to Markdown class"""
def extendMarkdown(self, md, md_globals):
"""Modifies inline patterns"""
md.inlinePatterns.add('test', PerceptionPattern(PATTERN), '<not_strong')
然而,这正在回归
<span>[]<a>test</a></span>
我不确定.tail
是正确的属性,但我没有找到正确的语法。
我怎样才能做到这一点?
完整程序
from markdown.inlinepatterns import Pattern
from markdown.util import etree
from markdown import Markdown
import markdown
PATTERN = r'\[(test)\]'
class TestPattern(Pattern):
def handleMatch(self, m):
span = etree.Element('span')
anchor = etree.SubElement(span, "a")
span.text = markdown.util.AtomicString("[")
span.tail = markdown.util.AtomicString("]")
#anchor.tail = markdown.util.AtomicString("]")
anchor.text = m.group(2)
return span
class TestExtension(markdown.extensions.Extension):
def extendMarkdown(self, md, md_globals):
"""Modifies inline patterns"""
md.inlinePatterns.add('test_pattern', TestPattern(PATTERN), '<not_strong')
md = Markdown(extensions=[TestExtension()])
print md.convert(u'[test]')