跳至主要内容

创建并高亮代码块

使用围栏代码块共享代码示例并启用语法高亮。

谁可以使用此功能?

Markdown 可在 GitHub 网页界面中使用。

围栏代码块

您可以通过在代码块前后放置三个反引号 ``` 来创建围栏代码块。我们建议在代码块前后留空行,以便更容易阅读原始格式。

```
function test() {
  console.log("notice the blank line before this function?");
}
```

Screenshot of rendered GitHub Markdown showing the use of triple backticks to create code blocks. The block begins with "function test() {."

提示

要在列表中保持格式,请确保将非围栏代码块缩进八个空格。

要在围栏代码块中显示三个反引号,请将它们包裹在四个反引号中。

````
```
Look! You can see my backticks.
```
````

Screenshot of rendered Markdown showing that when you write triple backticks between quadruple backticks they are visible in the rendered content.

如果您经常编辑代码片段和表格,启用 GitHub 所有评论字段的等宽字体可能会对您有所帮助。更多信息,请参阅 关于在 GitHub 上编写和格式化

语法高亮

您可以添加可选的语言标识符,以在围栏代码块中启用语法高亮。

语法高亮会更改源代码的颜色和样式,使其更易于阅读。

例如,要对 Ruby 代码进行语法高亮

```ruby
require 'redcarpet'
markdown = Redcarpet.new("Hello World!")
puts markdown.to_html
```

这将以语法高亮显示代码块

Screenshot of three lines of Ruby code as displayed on GitHub. Elements of the code display in purple, blue, and red type for scannability.

提示

在 GitHub Pages 站点上创建希望进行语法高亮的围栏代码块时,请使用小写语言标识符。欲了解更多信息,请参阅 关于 GitHub Pages 和 Jekyll

我们使用 Linguist 进行语言检测并选择 第三方语法 来实现语法高亮。您可以在 languages YAML 文件 中查看哪些关键字是有效的。

创建图表

您也可以使用代码块在 Markdown 中创建图表。GitHub 支持 Mermaid、GeoJSON、TopoJSON 和 ASCII STL 语法。欲了解更多信息,请参阅 创建图表

延伸阅读

© . This site is unofficial and not affiliated with GitHub, Inc.