美文网首页
Markdown小贴士

Markdown小贴士

作者: 老男人一枚的博客 | 来源:发表于2017-10-10 21:54 被阅读11次

    原文请点击这里

    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)
    

    相关文章

      网友评论

          本文标题:Markdown小贴士

          本文链接:https://www.haomeiwen.com/subject/ilnbyxtx.html