Congo 主题功能演示

本篇文章将演示 Hugo Congo 主题支持的三大核心功能:代码高亮、LaTeX 数学公式和 Mermaid 图表。

1. 代码高亮演示 #

Congo 主题内置 Hugo Chroma 代码高亮引擎,支持数百种编程语言。

Python 示例 #

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
def fibonacci(n: int) -> list[int]:
    """计算斐波那契数列前 n 项"""
    if n <= 0:
        return []
    elif n == 1:
        return [0]

    fib = [0, 1]
    for i in range(2, n):
        fib.append(fib[i-1] + fib[i-2])
    return fib

# 示例调用
result = fibonacci(10)
print(f"斐波那契数列前10项: {result}")

Go 示例 #

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package main

import (
    "fmt"
    "context"
)

func worker(ctx context.Context, id int, jobs <-chan int, results chan<- int) {
    for job := range jobs {
        select {
        case <-ctx.Done():
            fmt.Printf("Worker %d cancelled\n", id)
            return
        default:
            result := job * 2
            fmt.Printf("Worker %d processed job %d -> %d\n", id, job, result)
            results <- result
        }
    }
}

func main() {
    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()

    jobs := make(chan int, 100)
    results := make(chan int, 100)

    // 启动 3 个 worker
    for w := 1; w <= 3; w++ {
        go worker(ctx, w, jobs, results)
    }

    // 发送 10 个任务
    for j := 1; j <= 10; j++ {
        jobs <- j
    }
    close(jobs)

    // 收集结果
    for r := 1; r <= 10; r++ {
        <-results
    }
}

JavaScript 示例 #

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 异步迭代器处理流式数据
async function* streamProcessor(url) {
  const response = await fetch(url);
  const reader = response.body.getReader();
  const decoder = new TextDecoder();

  let buffer = '';
  while (true) {
    const { done, value } = await reader.read();
    if (done) break;

    buffer += decoder.decode(value, { stream: true });
    const lines = buffer.split('\n');
    buffer = lines.pop() ?? '';

    for (const line of lines) {
      if (line.trim()) {
        yield JSON.parse(line);
      }
    }
  }
}

// 使用示例
for await (const data of streamProcessor('/api/events')) {
  console.log('Received:', data);
}

Rust 示例 #

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
use std::collections::HashMap;

#[derive(Debug, Clone)]
pub struct LRUCache<K, V> {
    capacity: usize,
    cache: HashMap<K, V>,
    order: Vec<K>,
}

impl<K: Clone + std::hash::Hash + Eq, V> LRUCache<K, V> {
    pub fn new(capacity: usize) -> Self {
        Self {
            capacity,
            cache: HashMap::with_capacity(capacity),
            order: Vec::with_capacity(capacity),
        }
    }

    pub fn get(&mut self, key: &K) -> Option<&V> {
        if let Some(value) = self.cache.get(key) {
            self.order.retain(|k| k != key);
            self.order.push(key.clone());
            Some(value)
        } else {
            None
        }
    }

    pub fn put(&mut self, key: K, value: V) {
        if self.cache.contains_key(&key) {
            self.order.retain(|k| k != &key);
        } else if self.cache.len() >= self.capacity {
            if let Some(lru_key) = self.order.first().cloned() {
                self.cache.remove(&lru_key);
                self.order.remove(0);
            }
        }
        self.cache.insert(key.clone(), value);
        self.order.push(key);
    }
}

Shell 示例 #

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/bin/bash
# Docker 容器健康检查脚本

CONTAINER_NAME="myapp"
MAX_RETRIES=30
RETRY_INTERVAL=2

check_container_health() {
    local status=$(docker inspect --format='{{.State.Health.Status}}' $CONTAINER_NAME 2>/dev/null)

    case $status in
        "healthy")
            echo "✓ 容器状态正常"
            return 0
            ;;
        "unhealthy")
            echo "✗ 容器状态异常"
            docker logs --tail 50 $CONTAINER_NAME
            return 1
            ;;
        "starting")
            echo "⏳ 容器正在启动..."
            return 2
            ;;
        *)
            echo "✗ 无法获取容器状态"
            return 3
            ;;
    esac
}

echo "开始健康检查..."
for i in $(seq 1 $MAX_RETRIES); do
    echo "尝试 $i/$MAX_RETRIES"

    check_container_health
    status=$?

    if [ $status -eq 0 ]; then
        echo "健康检查通过"
        exit 0
    elif [ $status -eq 1 ]; then
        exit 1
    fi

    sleep $RETRY_INTERVAL
done

echo "健康检查超时"
exit 1

2. LaTeX 数学公式演示 #

行内公式 #

质能方程 $E = mc^2$ 是物理学中最著名的公式之一。

块级公式 #

2.1 线性代数 #

矩阵乘法:

$$ \begin{align} \begin{bmatrix} a_{11} & a_{12} & a_{13} \\ a_{21} & a_{22} & a_{23} \\ a_{31} & a_{32} & a_{33} \end{bmatrix} \begin{bmatrix} x_1 \\ x_2 \\ x_3 \end{bmatrix} = \begin{bmatrix} b_1 \\ b_2 \\ b_3 \end{bmatrix} \end{align} $$

2.2 微积分 #

泰勒展开式:

$$ f(x) = f(a) + \frac{f'(a)}{1!}(x-a) + \frac{f''(a)}{2!}(x-a)^2 + \cdots + \frac{f^{(n)}(a)}{n!}(x-a)^n + R_n(x) $$

2.3 概率论 #

正态分布概率密度函数:

$$ f(x) = \frac{1}{\sigma\sqrt{2\pi}} e^{-\frac{(x-\mu)^2}{2\sigma^2}} $$

2.4 复杂公式 #

傅里叶变换:

$$ \hat{f}(\xi) = \int_{-\infty}^{\infty} f(x) e^{-2\pi i x \xi} dx $$

3. Mermaid 图表演示 #

3.1 流程图 #

graph TD A[开始] --> B{是否有 Hugo} B -->|是| C[安装 Congo 主题] B -->|否| D[安装 Hugo Extended] D --> C C --> E[配置主题参数] E --> F[创建内容] F --> G[预览效果] G --> H{满意?} H -->|是| I[部署上线] H -->|否| E I --> J[完成]

3.2 时序图 #

sequenceDiagram participant U as 用户 participant B as 浏览器 participant S as 服务器 participant D as 数据库 U->>B: 访问博客首页 B->>S: GET /index.html S->>D: 查询文章列表 D-->>S: 返回文章数据 S-->>B: 返回 HTML + CSS + JS B-->>U: 渲染页面 Note over U,D: 用户开始阅读文章 U->>B: 点击文章链接 B->>S: GET /posts/xxx/ S->>D: 查询文章详情 D-->>S: 返回文章内容 S-->>B: 返回文章页面 B-->>U: 显示文章内容

3.3 状态图 #

stateDiagram-v2 [*] --> 待支付 待支付 --> 已支付: 支付成功 待支付 --> 已取消: 超时/取消 已支付 --> 配货中: 商家发货 配货中 --> 运输中: 快递揽收 运输中 --> 已签收: 确认收货 已签收 --> [*] 已取消 --> [*]

3.4 类图 #

classDiagram class Animal { +String name +int age +makeSound() void } class Dog { +String breed +fetch() void } class Cat { +boolean indoor +scratch() void } class Bird { +double wingSpan +fly() void } Animal <|-- Dog: 继承 Animal <|-- Cat: 继承 Animal <|-- Bird: 继承

总结 #

以上演示涵盖了:

  • 代码高亮: Python, Go, JavaScript, Rust, Shell 等多种语言
  • LaTeX: 行内公式、块级公式、矩阵、积分、概率等复杂公式
  • Mermaid: 流程图、时序图、状态图、类图等多种图表类型

Congo 主题完美支持这些功能,让你的技术博客更加专业美观!