推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
Hopetree
V2EX  ›  Python

Python 的 markdown 库使用了 markdown.extensions.codehilite 拓展不显示代码块的语言类型

  •  
  •   Hopetree ·
    Hopetree · Apr 24, 2023 · 2106 views
    This topic created in 1251 days ago, the information mentioned may be changed or developed.

    如题,我使用了 markdown 模型,然后正常渲染了文本,也可以代码高亮,但是我发现生成的 html 里面没有代码块的语言类型,比如下面这个代码块的 python 就是语言类型,正常的解析应该可以在 html 里面出现语言类型

    我的代码如下(代码块的符号改成了···避免发出来有问题):

    import markdown
    from markdown.extensions.toc import TocExtension
    from markdown.extensions.codehilite import CodeHiliteExtension, CodeHilite
    
    text = """
    ···python
    def test():
        print 2
        return 1
        
    ···
    """
    
    md = markdown.Markdown(extensions=[
        'markdown.extensions.extra',
        # 'markdown.extensions.fenced_code',
        'markdown.extensions.codehilite',
    ])
    
    print(md.convert(text))
    

    输出如下:

    <div class="codehilite"><pre><span></span><span class="k">def</span> <span class="nf">test</span><span class="p">():</span>
        <span class="nb">print</span> <span class="mi">2</span>
        <span class="k">return</span> <span class="mi">1</span>
    </pre></div>
    

    这个输出里面是缺少了语言类型的,我如果只用 markdown.extensions.fenced_code 是有语言类型,但是没有代码高亮,这两个插件还不能混着用,

    有大佬弄过类似的吗

    Hopetree
        1
    Hopetree  
    OP
       Apr 24, 2023
    官方文档找到了方法,问题解决了
    https://python-markdown.github.io/extensions/code_hilite/#usage

    文档最后面说了这个问题,提供了解决方案,可行
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2687 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 06:30 · PVG 14:30 · LAX 23:30 · JFK 02:30
    ♥ Do have faith in what you're doing.