mistune结合pygments,自定义展现
#-*- coding: utf-8 -*-
import re
import mistune
from pygments import highlight
from pygments.lexers import get_lexer_by_name, get_all_lexers
from pygments.formatters import html
class ExtRenderer(mistune.Renderer):
def block_code(self, code, lang):
if not lang :
return '\n<pre><code>%s</code></pre>\n' % \
mistune.escape(code)
try:
lexer = get_lexer_by_name(lang, stripall=True)
except:
return '\n<pre><code>%s</code></pre>\n' % \
mistune.escape(code)
formatter = html.HtmlFormatter()
return highlight(code, lexer, formatter)
def link(self, link, title, text):
u'''
新窗口打开超链接
'''
if link.startswith('javascript:'):
link = ''
if not title:
return '<a href="%s" target="_blank">%s</a>' % (link, text)
title = escape(title, quote=True)
return '<a href="%s" title="%s" target="_blank">%s</a>' % (link, title, text)
def ext_center(self, text):
u'''
居中显示
'''
return '<p align="center">%s</p>' % text
class ExtInlineLexer(mistune.InlineLexer):
def enable_ext_center(self):
# add wiki_link rules
self.rules.ext_center = re.compile(
r'\[\[' # [[
r'([\s\S]+?)' # text
r'\]\](?!\])' # ]]
)
self.default_rules.insert(3, 'ext_center')
def output_ext_center(self, m):
text = m.group(1)
text = self.output(text)
return self.renderer.ext_center(text)
Flask过滤器
@app.template_filter('markdown')
def markdown(value):
u'''
markdown
'''
renderer = ExtRenderer()
inline = ExtInlineLexer(renderer)
inline.enable_ext_center()
markdown = mistune.Markdown(renderer=renderer, inline=inline)
return markdown(value)