<pre>标记中的语法突出显示

2024-04-25 19:35:00 发布

您现在位置:Python中文网/ 问答频道 /正文

是否有库允许我在<pre>标记中显示代码并根据语言突出显示语法?我在想象这样的事情:

<pre class="python">
class MyClass:
    """A simple example class"""
    i = 12345
    def f(self):
        return 'hello world'
</pre>

…其中,pre.python的CSS将适当地突出显示Python代码。

有这样的东西吗?


Tags: 代码标记self语言helloreturnexampledef
3条回答

我更喜欢highlight.js。它支持112 languages

使用此代码注入从浏览器控制台预览页面:

// Highlight 22 popular code types. TODO: Inline for speed and security.
function loadjscssfile(filename, filetype){  // http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
    if(filetype=="js"){
        var fileref=document.createElement('script')
        fileref.setAttribute("type","text/javascript")
        fileref.setAttribute("src", filename)
    }
    else if(filetype=="css"){
        var fileref=document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", filename)
    }
    if(typeof fileref!="undefined") document.getElementsByTagName("head")[0].appendChild(fileref)
}
loadjscssfile("//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/vs.min.css", "css")
loadjscssfile("//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js", "js")
setTimeout("var a = document.querySelectorAll('.code'); for(var i=0; i < a.length; ++i) hljs.highlightBlock(a[i])", 600)

是的。您可以使用SyntaxHighlighter。它很容易使用正是你需要的方式。只需添加代码类。

它强调了包括Python在内的23种重要语言。

Download it right from here

希望这会有帮助。

SyntaxHighlighter

<pre class="brush: python">
   # python code here
</pre>

还有highlight.js可以选择自动检测语法并适当地突出显示它;但是,您需要同时使用<pre><code>标记来包装代码。

如果您正在寻找一个服务器端示例,那么Python中有GeSHiPygments

相关问题 更多 >