Display code (HTML, CSS, PHP, JavaScript, jQuery, etc.) on a webpage, just like code is displayed here, in a box, syntax-highlighted

后端 未结 5 1696
不知归路
不知归路 2021-02-20 06:07

I\'d like to display code on a web page. However I\'d like it to keep its spacing and be color coded by syntax.

Please do not respond with:

相关标签:
5条回答
  • 2021-02-20 06:32

    This is what you need to do:

    1. Replace < > & " with entities such as &lt; You do this, then do #2 to preserve spacing. You cannot avoid escaping entities since those characters can cause invalid HTML which causes parsing errors in the browser.
    2. Use <pre><code> to preserve spacing. After you escaped those special characters, and will not cause the escaped HTML and PHP to get executed (unless you explicitly told PHP and HTML to execute them).

    Syntax coloring is a bit more difficult, since you will need a parser that understands the language you're trying to show; even Stack Overflow's syntax coloring does not always work as well as it could.

    0 讨论(0)
  • 2021-02-20 06:40

    See Mark's references or check out this previous post. It works well.

    0 讨论(0)
  • 2021-02-20 06:42

    I use the syntax highlighter from Alex Gorbatchev (JavaScript).

    See http://alexgorbatchev.com/SyntaxHighlighter/manual/installation.html for instructions. But if you need to support displaying HTML containing script elements, you'll need to fall back to the <pre> method, and thus escape <, > and &.

    0 讨论(0)
  • 2021-02-20 06:47

    Look at PHP's built-in highlight_string() and highlight_file() functions.

    0 讨论(0)
  • 2021-02-20 06:52

    You can use SyntaxHighlighter.

    Download SyntaxHighlighter.

    The SyntaxHighlighter plugin is also available for WordPress users.

    For details, read this post.

    0 讨论(0)
提交回复
热议问题