代码高亮测试

杂项  ·  2026-01-15

Highlight.js 代码高亮插件测试

本文用于测试 Typecho 的 Highlight.js 插件在常用编程语言下的代码高亮效果。

前端语言

JavaScript

// ES6+ JavaScript 示例
class BlogPost {
    constructor(title, content) {
        this.title = title;
        this.content = content;
        this.tags = [];
    }

    addTag(tag) {
        this.tags.push(tag);
        console.log(`✅ 标签 "${tag}" 已添加`);
    }

    // 异步获取数据
    async fetchComments() {
        try {
            const response = await fetch(`/api/comments/${this.id}`);
            const data = await response.json();
            return data;
        } catch (error) {
            console.error('获取评论失败:', error);
        }
    }
}

// 箭头函数和解构
const posts = [
    { id: 1, title: '第一篇文章' },
    { id: 2, title: '第二篇文章' }
];

const titles = posts.map(({ title }) => title);

TypeScript

// TypeScript 类型系统
interface Article {
    id: string;
    title: string;
    content: string;
    tags: string[];
    publishedAt?: Date;
}

type ArticleStatus = 'draft' | 'published' | 'archived';

class BlogService {
    private articles: Map<string, Article> = new Map();

    getArticle(id: string): Article | undefined {
        return this.articles.get(id);
    }

    publishArticle(id: string): void {
        const article = this.articles.get(id);
        if (article) {
            article.publishedAt = new Date();
        }
    }
}

HTML

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>weDream Team | 小梦想 新可能</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <header class="site-header">
        <h1>微梦团队技术博客</h1>
        <nav>
            <a href="#home">首页</a>
            <a href="#blog">博客</a>
            <a href="#about">关于</a>
        </nav>
    </header>
    <main>
        <article class="post">
            <h2>欢迎来到我们的博客</h2>
            <p>这里是我们分享技术与创新的地方。</p>
        </article>
    </main>
    <script src="app.js"></script>
</body>
</html>

CSS

/* 现代 CSS 样式 */
:root {
    --primary-color: #3498db;
    --secondary-color: #2ecc71;
    --font-sans: 'SF Pro Display', -apple-system, sans-serif;
}

.site-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 2rem;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.site-header h1 {
    color: white;
    font-size: clamp(1.5rem, 4vw, 2.5rem);
    text-align: center;
    margin: 0;
}

.post {
    max-width: 800px;
    margin: 2rem auto;
    padding: 2rem;
    background: white;
    border-radius: 8px;
    transition: transform 0.3s ease;
}

.post:hover {
    transform: translateY(-4px);
    box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
}

/* 响应式设计 */
@media (max-width: 768px) {
    .site-header {
        padding: 1rem;
    }
}

后端语言

Python

# Python Flask 博客示例
from datetime import datetime
from typing import List, Optional

class Article:
    """博客文章类"""
    def __init__(self, title: str, content: str, author: str):
        self.title = title
        self.content = content
        self.author = author
        self.tags: List[str] = []
        self.created_at = datetime.now()
    
    def add_tag(self, tag: str) -> None:
        if tag not in self.tags:
            self.tags.append(tag)
    
    def get_summary(self, length: int = 100) -> str:
        return self.content[:length] + '...' if len(self.content) > length else self.content

# 列表推导式
def filter_by_tag(articles: List[Article], tag: str) -> List[Article]:
    return [article for article in articles if tag in article.tags]

# 装饰器示例
def require_login(func):
    def wrapper(*args, **kwargs):
        if not is_logged_in():
            return "请先登录"
        return func(*args, **kwargs)
    return wrapper

@require_login
def create_article(title: str, content: str):
    article = Article(title, content, get_current_user())
    return article

PHP

<?php
// PHP 8+ 博客系统
declare(strict_types=1);

namespace WeDream\Blog;

readonly class Article
{
    public function __construct(
        public string $id,
        public string $title,
        public string $content,
        public array $tags,
        public \DateTime $createdAt,
    ) {}
}

enum ArticleStatus: string
{
    case DRAFT = 'draft';
    case PUBLISHED = 'published';
    case ARCHIVED = 'archived';
}

class BlogRepository
{
    public function __construct(
        private \PDO $db
    ) {}

    public function findById(string $id): ?Article
    {
        $stmt = $this->db->prepare(
            "SELECT * FROM articles WHERE id = :id"
        );
        $stmt->execute(['id' => $id]);
        
        return $stmt->fetchObject(Article::class) ?: null;
    }

    public function searchByTag(string $tag, int $limit = 10): array
    {
        $stmt = $this->db->prepare(
            "SELECT * FROM articles 
             WHERE tags LIKE :tag 
             LIMIT :limit"
        );
        
        $stmt->execute([
            'tag' => "%{$tag}%",
            'limit' => $limit,
        ]);
        
        return $stmt->fetchAll(\PDO::FETCH_CLASS, Article::class);
    }
}

Java

// Java Spring Boot 示例
package team.wedream.blog;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

public record Article(
    String id,
    String title,
    String content,
    List<String> tags,
    LocalDateTime createdAt
) {}

public interface BlogRepository {
    Optional<Article> findById(String id);
    List<Article> findByTag(String tag);
    void save(Article article);
}

@RestController
@RequestMapping("/api/articles")
public class ArticleController {
    
    private final BlogRepository repository;
    
    public ArticleController(BlogRepository repository) {
        this.repository = repository;
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<Article> getArticle(@PathVariable String id) {
        return repository.findById(id)
            .map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
    }
    
    @GetMapping
    public List<Article> searchByTag(@RequestParam String tag) {
        return repository.findByTag(tag);
    }
}

Go

// Go 语言 Web 服务
package main

import (
    "encoding/json"
    "net/http"
    "time"
)

// Article 文章结构体
type Article struct {
    ID        string    `json:"id"`
    Title     string    `json:"title"`
    Content   string    `json:"content"`
    Tags      []string  `json:"tags"`
    CreatedAt time.Time `json:"created_at"`
}

// BlogService 博客服务
type BlogService struct {
    articles map[string]*Article
}

func NewBlogService() *BlogService {
    return &BlogService{
        articles: make(map[string]*Article),
    }
}

func (s *BlogService) GetArticle(id string) (*Article, error) {
    article, ok := s.articles[id]
    if !ok {
        return nil, fmt.Errorf("article not found: %s", id)
    }
    return article, nil
}

// HTTP 处理器
func (s *BlogService) HandleGetArticle(w http.ResponseWriter, r *http.Request) {
    id := r.URL.Query().Get("id")
    
    article, err := s.GetArticle(id)
    if err != nil {
        http.Error(w, err.Error(), http.StatusNotFound)
        return
    }
    
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(article)
}

数据库

SQL

-- PostgreSQL 示例

-- 创建表
CREATE TABLE articles (
    id SERIAL PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    content TEXT,
    author_id INTEGER REFERENCES users(id),
    status VARCHAR(20) DEFAULT 'draft',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 创建索引
CREATE INDEX idx_articles_status ON articles(status);
CREATE INDEX idx_articles_author ON articles(author_id);

-- 复杂查询:使用 CTE 和窗口函数
WITH ranked_articles AS (
    SELECT 
        a.*,
        u.name AS author_name,
        ROW_NUMBER() OVER (
            PARTITION BY a.author_id 
            ORDER BY a.created_at DESC
        ) AS rank
    FROM articles a
    JOIN users u ON a.author_id = u.id
    WHERE a.status = 'published'
)
SELECT *
FROM ranked_articles
WHERE rank <= 5
ORDER BY author_id, rank;

-- JSON 操作
SELECT 
    title,
    metadata->>'category' AS category,
    metadata->'tags' AS tags
FROM articles
WHERE metadata @> '{"featured": true}';

-- 聚合查询
SELECT 
    u.name,
    COUNT(*) AS article_count,
    MAX(a.created_at) AS last_posted
FROM articles a
JOIN users u ON a.author_id = u.id
GROUP BY u.id, u.name
HAVING COUNT(*) > 5
ORDER BY article_count DESC;

配置文件

JSON

{
  "name": "wedream-blog",
  "version": "1.0.0",
  "description": "weDream Team 技术博客",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "vue": "^3.4.0",
    "vue-router": "^4.2.0"
  },
  "devDependencies": {
    "vite": "^5.0.0",
    "typescript": "^5.3.0"
  }
}

YAML

# Docker Compose 配置
version: '3.8'

services:
  blog:
    image: wedream/blog:latest
    container_name: wedream_blog
    ports:
      - "3000:3000"
    environment:
      NODE_ENV: production
      DATABASE_URL: postgresql://user:pass@db:5432/blog
    volumes:
      - ./uploads:/app/uploads
    depends_on:
      - db

  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_DB: blog
      POSTGRES_USER: user
      POSTGRES_PASSWORD: ${DB_PASSWORD}
    volumes:
      - postgres_data:/var/lib/postgresql/data

volumes:
  postgres_data:

Bash

#!/bin/bash
# 博客部署脚本

set -e

PROJECT_DIR="/var/www/wedream-blog"
LOG_FILE="/var/log/deploy.log"

log() {
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOG_FILE"
}

deploy() {
    log "开始部署..."
    
    cd "$PROJECT_DIR"
    git pull origin main
    
    npm ci --production
    npm run build
    
    systemctl restart wedream-blog
    
    log "部署完成 ✅"
}

deploy

测试说明

以上代码涵盖了博客开发中常用的语言:

  • 前端: JavaScript, TypeScript, HTML, CSS
  • 后端: Python, PHP, Java, Go
  • 数据库: SQL (PostgreSQL)
  • 配置: JSON, YAML, Bash
 
上一篇:没有了
下一篇:没有了
评论
weDreamTeam. All Rights Reserved.