代码高亮测试

本文用于测试新的代码高亮功能,包括语法高亮、复制按钮、语言显示等。

JavaScript

JAVASCRIPT

function fibonacci(n) {
  if (n <= 1) return n;
  return fibonacci(n - 1) + fibonacci(n - 2);
}


const result = fibonacci(10);
console.log(`第10个斐波那契数是:${result}`);

// 异步/等待
const asyncFunction = async () => {
  try {
    const response = await fetch('/api/data');
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('获取数据时出错:', error);
  }
};
点击展开查看更多

带行号的代码块

PYTHON
 1# 带行号的 Python 代码
 2import asyncio
 3from typing import List, Optional
 4
 5class DataProcessor:
 6    def __init__(self, data: List[dict]):
 7        self.data = data
 8
 9    def process(self) -> Optional[dict]:
10        """处理数据并返回结果"""
11        if not self.data:
12            return None
13
14        result = {
15            'total': len(self.data),
16            'processed': []
17        }
18
19        for item in self.data:
20            if self.validate_item(item):
21                result['processed'].append(item)
22
23        return result
点击展开查看更多

高亮特定行

GO
 1package main
 2
 3import "fmt"  // 这一行将被高亮
 4
 5func main() {
 6    message := "你好,世界!"  // 这一行也将被高亮
 7
 8    fmt.Println(message)  // 这一行也将被高亮
 9
10    for i := 0; i < 3; i++ {
11        fmt.Printf("计数:%d\n", i)
12    }
13}
点击展开查看更多

带文件名的代码块

api.ts
// TypeScript API
interface ApiResponse<T> {
  data: T;
  status: number;
  message: string;
}

interface User {
  id: number;
  name: string;
  email: string;
  avatar?: string;
}

class ApiClient {
  private baseURL: string;
  private headers: Record<string, string>;

  constructor(baseURL: string, apiKey?: string) {
    this.baseURL = baseURL;
    this.headers = {
      'Content-Type': 'application/json',
      ...(apiKey && { 'Authorization': `Bearer ${apiKey}` })
    };
  }

  async get<T>(endpoint: string): Promise<ApiResponse<T>> {
    const response = await fetch(`${this.baseURL}${endpoint}`, {
      method: 'GET',
      headers: this.headers,
    });

    if (!response.ok) {
      throw new Error(`HTTP 错误!状态:${response.status}`);
    }

    return response.json();
  }

  async post<T>(endpoint: string, data: any): Promise<ApiResponse<T>> {
    const response = await fetch(`${this.baseURL}${endpoint}`, {
      method: 'POST',
      headers: this.headers,
      body: JSON.stringify(data),
    });

    return response.json();
  }
}

const client = new ApiClient('https://api.example.com', 'your-api-key');

async function getUsers(): Promise<User[]> {
  try {
    const response = await client.get<User[]>('/users');
    return response.data;
  } catch (error) {
    console.error('获取用户时出错:', error);
    return [];
  }
}
点击展开查看更多

纯文本代码块

PLAINTEXT
这是一个纯文本代码块。
它不应该有语法高亮。
你可以在这里测试复制功能。

function test() {
    console.log("这是一个测试。");
}
点击展开查看更多

行内代码

这是一个行内代码示例:const x = 42;npm install 以及 git commit -m "更新"


版权声明

作者: 名字还没想好

链接: http://localhost:1313/posts/code-highlighting-test/

许可证: CC BY-NC-SA 4.0

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Please attribute the source, use non-commercially, and maintain the same license.

评论

开始搜索

输入关键词搜索文章内容

↑↓
ESC
⌘K 快捷键