跳到导航

代码块

以 Markdown 格式查看

<CodeBlock> 组件用于显示带语法高亮的代码示例。代码块支持行高亮、聚焦、标题和深度链接,让您的代码示例更易读、更具交互性。

用法

使用三个反引号,并可选地添加语言标识符。

console.log("hello world")
Markdown
```js
console.log("hello world")
```
支持的语言

Fern 通过 Shiki 为以下语言提供语法高亮支持:

  • javascript (别名:js、node)
  • python
  • java
  • typescript (别名:ts)
  • csharp
  • cpp
  • c
  • php
  • go
  • rust
  • ruby
  • swift
  • kotlin
  • sql
  • bash (别名:shell、sh)
  • curl
  • markdown (别名:md)
  • http

如果您指定了不在该列表中的语言,Fern 仍会显示代码块,但不会进行语法高亮。

变体

标题

在语言标识符之后添加标题,即可为代码片段添加标题。或者使用 title 属性(title="带标题的片段")或 filename 属性(filename="带标题的片段")实现相同效果。

带标题的片段
console.log("hello world")
Markdown
```js 带标题的片段
console.log("hello world")
```

行高亮

通过在语言标识符后的 {} 中放入数字范围,可以高亮代码片段中的特定行。范围为闭区间,可以是单个数字、用逗号分隔的多个数字,或区间。

console.log("Line 1");
console.log("Line 2");
console.log("Line 3");
console.log("Line 4");
console.log("Line 5");
console.log("Line 6");
Markdown
```javascript {2-4, 6}
console.log("Line 1");
console.log("Line 2");
console.log("Line 3");
console.log("Line 4");
console.log("Line 5");
console.log("Line 6");
```

行聚焦

通过添加注释 [!code focus],或在语言标识符后添加 focus 属性,可聚焦特定行。

console.log("Line 1");
console.log("Line 2");
console.log("Line 3");
console.log("Line 4");
console.log("Line 5");
Markdown
```javascript focus={2-4}
console.log("Line 1");
console.log("Line 2");
console.log("Line 3");
console.log("Line 4");
console.log("Line 5");
```

起始行号

通过在语言标识符后添加 startLine 属性,可控制代码块中显示的第一行行号。这对较长的代码片段非常有用——既能突出主要逻辑,又能保留完整上下文。

console.log("Line 1");
console.log("Line 2");
console.log("Line 3");
console.log("Line 4");
console.log("Line 5");
console.log("Line 6");
console.log("Line 7");
console.log("Line 8");
console.log("Line 9");
console.log("Line 10");
console.log("Line 11");
console.log("Line 12");
console.log("Line 13");
console.log("Line 14");
console.log("Line 15");
console.log("Line 16");
console.log("Line 17");
console.log("Line 18");
console.log("Line 19");
console.log("Line 20");
console.log("Line 21");
console.log("Line 22");
console.log("Line 23");
console.log("Line 24");
console.log("Line 25");
console.log("Line 26");
console.log("Line 27");
console.log("Line 28")
Markdown
```javascript startLine={6}
console.log("Line 1");
console.log("Line 2");
console.log("Line 3");
console.log("Line 4");
console.log("Line 5");
console.log("Line 6");
console.log("Line 7");
console.log("Line 8");
console.log("Line 9");
console.log("Line 10");
console.log("Line 11");
console.log("Line 12");
console.log("Line 13");
console.log("Line 14");
console.log("Line 15");
console.log("Line 16");
console.log("Line 17");
console.log("Line 18");
console.log("Line 19");
console.log("Line 20");
console.log("Line 21");
console.log("Line 22");
console.log("Line 23");
console.log("Line 24");
console.log("Line 25");
console.log("Line 26");
console.log("Line 27");
console.log("Line 28")
```

最大高度

在语言标识符后添加 maxLines 属性可控制代码块的最大高度。maxLines 应为表示最大显示行数的数字。默认情况下,代码块最多显示 20 行。(如需禁用默认 20 行限制,请将 maxLines 设为 0。)

当您使用 maxLines 时,鼠标悬停时右上角会自动出现展开按钮,用户点击后可在覆盖在页面上的展开层中查看完整代码内容。

def is_prime(num):
"""Check if a number is prime."""
if num <= 1:
return False
for i in range(2, num):
if num % i == 0:
return False
return True
start = 10
end = 50
print(f"Prime numbers between {start} and {end} are:")
prime_numbers = []
for num in range(start, end+1):
if is_prime(num):
prime_numbers.append(num)
for prime in prime_numbers:
print(prime)
Markdown
```python maxLines=10
def is_prime(num):
"""Check if a number is prime."""
if num <= 1:
return False
for i in range(2, num):
if num % i == 0:
return False
return True
start = 10
end = 50
print(f"Prime numbers between {start} and {end} are:")
prime_numbers = []
for num in range(start, end+1):
if is_prime(num):
prime_numbers.append(num)
for prime in prime_numbers:
print(prime)
```
自定义样式

如需隐藏展开按钮或添加自定义样式,请针对 .fern-expand-button 选择器进行设置:

/* 隐藏展开按钮 */
.fern-expand-button {
display: none;
}

换行处理

默认情况下,超出代码块宽度的长行会变为可滚动:

Without wordWrap
A very very very long line of text that may cause the code block to overflow and scroll as a result.
Markdown
```txt title="Without wordWrap"
A very very very long line of text that may cause the code block to overflow and scroll as a result.
```

要禁用滚动并将超出部分换到下一行,请使用 wordWrap 属性:

With wordWrap
A very very very long line of text that may cause the code block to overflow and scroll as a result.
Markdown
```txt title="With wordWrap" wordWrap
A very very very long line of text that may cause the code block to overflow and scroll as a result.
```

隐藏行号

默认情况下,代码块会在边栏显示行号(在 bash/shell 代码块中还会显示 $ / > 前缀)。要隐藏行号和前缀,请将 showLineNumbers 设置为 false:

npm install plantstore
npm run build \
--output dist
Markdown
```bash showLineNumbers={false}
npm install plantstore
npm run build \
--output dist
```

深度链接

通过定义 links 映射,可让代码块中的特定文本变为可点击。这对从代码示例直接链接到文档、API 参考或相关资源非常有用。

links 属性接受一个映射,其中键为匹配模式(精确字符串或正则表达式),值为目标 URL。

import { PlantClient } from "@plantstore/sdk";
const client = new PlantClient({ apiKey: "YOUR_API_KEY" });
const plant = await client.createPlant({
name: "Monstera",
species: "Monstera deliciosa"
});
Markdown
<CodeBlock
links={{"PlantClient": "/learn/docs/writing-content/demo#plantclient", "createPlant": "/learn/docs/writing-content/demo#create_plant"}}
>
```typescript
import { PlantClient } from "@plantstore/sdk";
const client = new PlantClient({ apiKey: "YOUR_API_KEY" });
const plant = await client.createPlant({
name: "Monstera",
species: "Monstera deliciosa"
});
```
</CodeBlock>

links 属性使用 JSON 格式。映射中的每个键会与代码块中的文本进行精确匹配,匹配到的文本将变为指向对应 URL 的可点击链接。

您可以使用正则表达式实现更灵活的匹配。当您想要匹配多种文本变体或模式时,这非常有用。

在下面的示例中,/get\\w+/ 会同时匹配 getPlant 和 getGarden,而 /Plant(Store|Client)/ 会同时匹配 PlantStore 和 PlantClient。

from plantstore import PlantStore, PlantClient
store = PlantStore(api_key="YOUR_API_KEY")
client = PlantClient(store)
plant = store.getPlant(plant_id="123")
garden = store.getGarden(garden_id="456")
Markdown
<CodeBlock
links={{"/get\\w+/": "/learn/docs/writing-content/demo#get-methods", "/Plant(Store|Client)/": "/learn/docs/writing-content/demo#type-definitions"}}
>
```python
from plantstore import PlantStore, PlantClient
store = PlantStore(api_key="YOUR_API_KEY")
client = PlantClient(store)
plant = store.getPlant(plant_id="123")
garden = store.getGarden(garden_id="456")
```
</CodeBlock>

使用正则表达式时,请记得在 JSON 字符串中用双反斜杠转义特殊字符(例如 \\w+、\\d+)。

嵌入代码文件

通过在 <Code> 组件上使用 src 属性,可以嵌入本地或外部文件中的代码。对于本地文件,请使用相对于 docs 目录的路径;对于外部文件,请使用完整 URL,从 GitHub 等远程源直接拉取代码示例。

<Code> 组件支持与 <CodeBlock> 相同的所有属性,包括 title、language 和 maxLines。

Local file
console.log("I love Fern!");
example-code.js
console.log("I also love Fern!");
Markdown
```js
console.log("I love Fern!");
```
<Code src="snippets/example-code.js">
GitHub Actions 工作流(外部文件)
name: fern-check
on:
pull_request:
push:
branches:
- main
jobs:
run:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v5
- name: Setup Node.js
uses: actions/setup-node@v5
with:
node-version: "24"
- name: Setup Fern CLI
uses: fern-api/setup-fern-cli@v1
- name: Check API is valid
run: fern check
Markdown
<Code
src="https://raw.githubusercontent.com/fern-api/docs-starter/refs/heads/main/.github/workflows/check.yml"
title="GitHub Actions workflow"
language="yaml"
maxLines={15}
>

带标签页的代码块

在标签页界面中显示多个代码块。

puts "Hello World"
Markdown
<CodeBlocks>
```ruby title="hello_world.rb"
puts "Hello World"
```
```php title="hello_world.php"
<?php
echo "Hello World";
?>
```
```rust title="hello_world.rs"
fn main() {
println!("Hello World");
}
```
</CodeBlocks>

语言同步

设置了相同语言的代码块会在整个文档站点中自动同步。当用户选择某种语言时,所有该语言的代码块都会同步切换。语言偏好会跨浏览器会话保留。

print("First code block!")
print("Second code block - syncs with the one above!")

代码块会自动与相同语言的标签页同步。

您可以通过在 URL 末尾添加 ?language=<某种语言> 来直接链接到特定语言的内容。这将设置用户访问页面时默认显示的语言标签。

例如,以下链接会默认显示 Java 标签页:https://buildwithfern.com/learn/docs/writing-content/components/tabs?language=java

这适用于具有 language 属性的 CodeBlocks 和 Tab 组件。

使用 for 属性可以创建独立于语言的自定义同步分组。这对于按其他维度分组代码块(例如按包管理器或框架)非常有用。

npm install plantstore
npm uninstall plantstore
Markdown
<CodeGroup>
```bash title="使用 npm 安装" for="npm"
npm install plantstore
```
```bash title="使用 pnpm 安装" for="pnpm"
pnpm add plantstore
```
```bash title="使用 yarn 安装" for="yarn"
yarn add plantstore
```
</CodeGroup>
<CodeGroup>
```bash title="使用 npm 卸载" for="npm"
npm uninstall plantstore
```
```bash title="使用 pnpm 卸载" for="pnpm"
pnpm remove plantstore
```
```bash title="使用 yarn 卸载" for="yarn"
yarn remove plantstore
```
</CodeGroup>

属性

代码块属性

这些属性可以在 markdown 代码块的语言标识符后添加,也可以作为 <CodeBlock> 组件的 props 使用。

language
string

用于语法高亮的编程语言。支持的语言:javascript(别名:js、node)、python、java、typescript(别名:ts)、csharp、cpp、c、php、go、rust、ruby、swift、kotlin、sql、bash(别名:shell、sh)、curl、markdown(别名:md)、http。

title
string

显示在代码块上方的标题。可以在语言标识符后内联指定,或通过 title="..." 或 filename="..." 属性指定。

highlight
string

要高亮的行,使用 {2-4, 6} 语法指定。支持单个数字、范围和逗号分隔的列表。

focus
string

要聚焦的行,使用 focus={2-4} 指定。用法与 highlight 相同,但会将未聚焦的行变暗。

startLine
number

开始显示的行号。在显示较长代码文件的特定部分时非常有用。

maxLines
numberDefaults to 20

开始添加滚动前显示的最大行数。设置为 0 可禁用此限制。

wordWrap
booleanDefaults to false

是否对长行进行换行处理(而非滚动显示)。

showLineNumbers
booleanDefaults to true

是否在边栏显示行号,包括 bash/shell 代码块中的命令提示符($ 和 >)。设置为 false 可隐藏行号,让代码示例外观更简洁。

for
string

自定义同步分组标识符。会覆盖默认的基于语言的同步行为。

links
object

文本模式到 URL 的映射,用于在代码内创建可点击链接。键可以是精确字符串或正则表达式(例如 {"/get\\w+/": "/api-docs"})。

<Code> 属性

<Code> 组件用于嵌入文件中的代码。它接受上面列出的所有代码块属性,外加:

src
stringRequired

本地文件路径(相对于 docs 目录)或外部文件的完整 URL(例如 GitHub raw URL)。

lines
number[]

从源文件中提取的行号。支持单行([5])、范围([2-4])和组合形式([1-3,5,7-10])。行号从 1 开始。