如何在 HTML 页面中显示代码(特别是 C++)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5710247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I show code (specifically C++) in an HTML page?
提问by hhdgfdg
How can I show code in a website using HTML? Basically, I have a C++ program that I'd like to share on my website and I want to show it in the page.
如何使用 HTML 在网站中显示代码?基本上,我有一个 C++ 程序,我想在我的网站上分享它,我想在页面中显示它。
Is there anyway to show a C++ code in HTML other than using HTML text?
除了使用 HTML 文本之外,还有没有在 HTML 中显示 C++ 代码的方法?
回答by jessegavin
You can use SyntaxHighlighter. It will unobtrusively enhance code samples on your page with specific syntax highlighting for a wide range of languages.
您可以使用SyntaxHighlighter。它将通过针对多种语言的特定语法突出显示来不显眼地增强页面上的代码示例。
Here's an example for C++
这是 C++ 的示例
<head>
<link href="css/shCore.css" rel="stylesheet" type="text/css" />
<link href="css/shThemeDefault.css" rel="stylesheet" type="text/css" />
</head>
<body>
<pre class='brush: cpp'>
// my first program in C++
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
return 0;
}
</pre>
<script src="js/shCore.js"></script>
<script src="js/shBrushCpp.js"></script>
<script>
SyntaxHighlighter.all()
</script>
</body>
回答by David
There are various syntax highlighters out there. Google Code Prettifyis a pretty good one. (Good enough for Stack Overflow to use, anyway.)
那里有各种语法荧光笔。 Google Code Prettify是一个不错的选择。(无论如何,Stack Overflow 已经足够使用了。)
回答by Paul D. Waite
HTML includes a tag called <code>
, which is meant for the purpose you describe.
HTML 包含一个名为 的标记<code>
,用于您描述的目的。
The spec even includes an example class name convention to indicate which language the code is in:
该规范甚至包括一个示例类名称约定,以指示代码使用的语言:
<pre><code class="language-pascal">var i: Integer;
begin
i := 1;
end.</code></pre>
I don't know of any web browser that supports such a convention (come on, Chrome), but the JavaScript syntax highlighters mentioned in other answers could use it to work their magic.
我不知道任何支持这种约定的网络浏览器(来吧,Chrome),但其他答案中提到的 JavaScript 语法荧光笔可以使用它来发挥它们的魔力。
As you can see in the example, the <code>
tag is usually wrapped in the <pre>
tag, which preserves white space, which is often important for code.
正如您在示例中看到的,<code>
标签通常被包裹在<pre>
标签中,它保留了空格,这对于代码来说通常很重要。