--
:
--
:
--
代码块语法
最后更新于:
🔤 代码块语言图标功能
本主题支持自动识别代码块语言并显示对应的官方品牌图标,提升代码可读性和视觉体验。
🎯 支持的编程语言
🌐 前端开发
JavaScript
1function greet(name) {
2 return `Hello, ${name}!`;
3}
4
5console.log(greet('World'));TypeScript
1interface User {
2 id: number;
3 name: string;
4 email: string;
5}
6
7const user: User = {
8 id: 1,
9 name: '张三',
10 email: 'zhangsan@example.com'
11};Vue
1<template>
2 <div class="hello">
3 <h1>{{ msg }}</h1>
4 <button @click="count++">Count: {{ count }}</button>
5 </div>
6</template>
7
8<script setup>
9import { ref } from 'vue'
10
11defineProps({
12 msg: String
13})
14
15const count = ref(0)
16</script>
17
18<style scoped>
19.hello {
20 text-align: center;
21}
22</style>HTML
1<!DOCTYPE html>
2<html lang="zh-CN">
3<head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>示例页面</title>
7</head>
8<body>
9 <header>
10 <h1>欢迎来到我的网站</h1>
11 </header>
12 <main>
13 <p>这是一个HTML示例。</p>
14 </main>
15</body>
16</html>CSS
1.card {
2 background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
3 border-radius: 12px;
4 padding: 24px;
5 box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
6 transition: transform 0.3s ease;
7}
8
9.card:hover {
10 transform: translateY(-4px);
11}SCSS
1// 变量定义
2$primary-color: #3498db;
3$secondary-color: #2ecc71;
4$border-radius: 8px;
5
6// 混合宏
7@mixin flex-center {
8 display: flex;
9 justify-content: center;
10 align-items: center;
11}
12
13// 嵌套规则
14.navbar {
15 background-color: $primary-color;
16 padding: 1rem;
17
18 &__list {
19 list-style: none;
20 @include flex-center;
21 gap: 2rem;
22 }
23
24 &__item {
25 color: white;
26
27 &:hover {
28 color: $secondary-color;
29 }
30 }
31}🖥️ 后端开发
PHP
1<?php
2
3class UserController {
4 private $db;
5
6 public function __construct(Database $db) {
7 $this->db = $db;
8 }
9
10 public function getUser(int $id): ?User {
11 $stmt = $this->db->prepare("SELECT * FROM users WHERE id = ?");
12 $stmt->execute([$id]);
13
14 $data = $stmt->fetch();
15 return $data ? new User($data) : null;
16 }
17
18 public function createUser(array $data): User {
19 $user = new User($data);
20 $user->save();
21 return $user;
22 }
23}Go
1package main
2
3import (
4 "fmt"
5 "net/http"
6 "time"
7)
8
9func main() {
10 http.HandleFunc("/", handler)
11
12 server := &http.Server{
13 Addr: ":8080",
14 Handler: nil,
15 ReadTimeout: 10 * time.Second,
16 WriteTimeout: 10 * time.Second,
17 }
18
19 fmt.Println("Server starting on :8080")
20 if err := server.ListenAndServe(); err != nil {
21 fmt.Printf("Server error: %v\n", err)
22 }
23}
24
25func handler(w http.ResponseWriter, r *http.Request) {
26 fmt.Fprintf(w, "Hello, %s!", r.URL.Path[1:])
27}Python
1from typing import List, Optional
2from dataclasses import dataclass
3
4@dataclass
5class Product:
6 id: int
7 name: str
8 price: float
9 category: str
10
11class ProductRepository:
12 def __init__(self):
13 self.products: List[Product] = []
14
15 def add(self, product: Product) -> None:
16 self.products.append(product)
17
18 def find_by_category(self, category: str) -> List[Product]:
19 return [p for p in self.products if p.category == category]
20
21 def find_by_id(self, product_id: int) -> Optional[Product]:
22 for product in self.products:
23 if product.id == product_id:
24 return product
25 return None
26
27# 使用示例
28repo = ProductRepository()
29repo.add(Product(1, "笔记本电脑", 5999.00, "电子产品"))
30repo.add(Product(2, "机械键盘", 899.00, "电子产品"))Java
1import java.util.ArrayList;
2import java.util.List;
3import java.util.Optional;
4
5public class UserService {
6 private final UserRepository userRepository;
7
8 public UserService(UserRepository userRepository) {
9 this.userRepository = userRepository;
10 }
11
12 public User createUser(String username, String email) {
13 if (username == null || username.isEmpty()) {
14 throw new IllegalArgumentException("用户名不能为空");
15 }
16
17 User user = new User();
18 user.setUsername(username);
19 user.setEmail(email);
20 user.setCreatedAt(LocalDateTime.now());
21
22 return userRepository.save(user);
23 }
24
25 public Optional<User> findById(Long id) {
26 return userRepository.findById(id);
27 }
28
29 public List<User> findAllActiveUsers() {
30 return userRepository.findByStatus(UserStatus.ACTIVE);
31 }
32}⚙️ Shell脚本
Bash
1#!/bin/bash
2
3# 定义变量
4APP_NAME="myapp"
5VERSION="1.0.0"
6LOG_DIR="/var/log/${APP_NAME}"
7
8# 创建日志目录
9mkdir -p "${LOG_DIR}"
10
11# 检查服务状态
12check_service() {
13 local service_name=$1
14 if systemctl is-active --quiet "${service_name}"; then
15 echo "✅ ${service_name} 正在运行"
16 return 0
17 else
18 echo "❌ ${service_name} 未运行"
19 return 1
20 fi
21}
22
23# 主逻辑
24echo "=== ${APP_NAME} v${VERSION} 部署脚本 ==="
25
26# 检查依赖服务
27check_service "nginx"
28check_service "mysql"
29
30# 备份旧版本
31if [ -d "/opt/${APP_NAME}" ]; then
32 BACKUP_NAME="${APP_NAME}_$(date +%Y%m%d_%H%M%S)"
33 mv "/opt/${APP_NAME}" "/opt/backups/${BACKUP_NAME}"
34 echo "📦 已备份旧版本: ${BACKUP_NAME}"
35fi
36
37# 部署新版本
38echo "🚀 开始部署..."
39# 部署逻辑...
40echo "✅ 部署完成!"🛠️ 系统编程
C
1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4
5typedef struct {
6 char name[50];
7 int age;
8 float score;
9} Student;
10
11Student* create_student(const char* name, int age, float score) {
12 Student* s = (Student*)malloc(sizeof(Student));
13 if (s == NULL) {
14 fprintf(stderr, "内存分配失败\n");
15 return NULL;
16 }
17
18 strncpy(s->name, name, sizeof(s->name) - 1);
19 s->name[sizeof(s->name) - 1] = '\0';
20 s->age = age;
21 s->score = score;
22
23 return s;
24}
25
26void print_student(const Student* s) {
27 if (s != NULL) {
28 printf("姓名: %s, 年龄: %d, 成绩: %.2f\n",
29 s->name, s->age, s->score);
30 }
31}
32
33int main() {
34 Student* student = create_student("张三", 20, 85.5);
35 print_student(student);
36
37 free(student);
38 return 0;
39}C#
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Threading.Tasks;
5
6namespace MyApp.Services
7{
8 public class ProductService : IProductService
9 {
10 private readonly IProductRepository _repository;
11 private readonly ILogger<ProductService> _logger;
12
13 public ProductService(
14 IProductRepository repository,
15 ILogger<ProductService> logger)
16 {
17 _repository = repository;
18 _logger = logger;
19 }
20
21 public async Task<Product> GetByIdAsync(int id)
22 {
23 _logger.LogInformation("获取产品: {ProductId}", id);
24 return await _repository.GetByIdAsync(id);
25 }
26
27 public async Task<IEnumerable<Product>> GetAllAsync()
28 {
29 return await _repository.GetAllAsync();
30 }
31
32 public async Task<Product> CreateAsync(Product product)
33 {
34 if (product == null)
35 throw new ArgumentNullException(nameof(product));
36
37 product.CreatedAt = DateTime.UtcNow;
38 return await _repository.AddAsync(product);
39 }
40 }
41}Rust
1use std::collections::HashMap;
2
3#[derive(Debug, Clone)]
4pub struct User {
5 id: u64,
6 username: String,
7 email: String,
8 active: bool,
9}
10
11pub struct UserRepository {
12 users: HashMap<u64, User>,
13 next_id: u64,
14}
15
16impl UserRepository {
17 pub fn new() -> Self {
18 Self {
19 users: HashMap::new(),
20 next_id: 1,
21 }
22 }
23
24 pub fn create(&mut self, username: String, email: String) -> &User {
25 let id = self.next_id;
26 self.next_id += 1;
27
28 let user = User {
29 id,
30 username,
31 email,
32 active: true,
33 };
34
35 self.users.insert(id, user);
36 self.users.get(&id).unwrap()
37 }
38
39 pub fn find_by_id(&self, id: u64) -> Option<&User> {
40 self.users.get(&id)
41 }
42
43 pub fn find_active(&self) -> Vec<&User> {
44 self.users
45 .values()
46 .filter(|u| u.active)
47 .collect()
48 }
49}
50
51fn main() {
52 let mut repo = UserRepository::new();
53
54 let user = repo.create(
55 String::from("张三"),
56 String::from("zhangsan@example.com")
57 );
58
59 println!("创建用户: {:?}", user);
60}Kotlin
1package com.example.app
2
3import kotlinx.coroutines.*
4import java.time.LocalDateTime
5
6data class User(
7 val id: Long,
8 val username: String,
9 val email: String,
10 val createdAt: LocalDateTime = LocalDateTime.now()
11)
12
13class UserRepository {
14 private val users = mutableListOf<User>()
15 private var nextId = 1L
16
17 fun create(username: String, email: String): User {
18 require(username.isNotBlank()) { "用户名不能为空" }
19 require(email.contains("@")) { "邮箱格式不正确" }
20
21 val user = User(
22 id = nextId++,
23 username = username,
24 email = email
25 )
26 users.add(user)
27 return user
28 }
29
30 fun findById(id: Long): User? = users.find { it.id == id }
31
32 fun findAll(): List<User> = users.toList()
33
34 suspend fun fetchUserAsync(id: Long): User? = withContext(Dispatchers.IO) {
35 delay(100) // 模拟网络延迟
36 findById(id)
37 }
38}
39
40// 使用示例
41suspend fun main() {
42 val repository = UserRepository()
43
44 val user = repository.create("张三", "zhangsan@example.com")
45 println("创建用户: $user")
46
47 val fetchedUser = repository.fetchUserAsync(user.id)
48 println("获取用户: $fetchedUser")
49}📝 数据库
SQL
1SELECT u.id, u.username, u.email, COUNT(o.id) as order_count
2FROM users u
3LEFT JOIN orders o ON u.id = o.user_id
4WHERE u.status = 'active'
5GROUP BY u.id, u.username, u.email
6HAVING COUNT(o.id) > 5
7ORDER BY order_count DESC
8LIMIT 10;MySQL
1-- 创建用户表
2CREATE TABLE users (
3 id INT AUTO_INCREMENT PRIMARY KEY,
4 username VARCHAR(50) NOT NULL UNIQUE,
5 email VARCHAR(100) NOT NULL UNIQUE,
6 password_hash VARCHAR(255) NOT NULL,
7 status ENUM('active', 'inactive', 'banned') DEFAULT 'active',
8 created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
9 updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
10 INDEX idx_status (status),
11 INDEX idx_created_at (created_at)
12) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
13
14-- 插入测试数据
15INSERT INTO users (username, email, password_hash) VALUES
16('张三', 'zhangsan@example.com', '$2y$10$...'),
17('李四', 'lisi@example.com', '$2y$10$...');PostgreSQL
1-- 创建带有JSONB字段的表
2CREATE TABLE products (
3 id SERIAL PRIMARY KEY,
4 name VARCHAR(255) NOT NULL,
5 price DECIMAL(10, 2) NOT NULL CHECK (price >= 0),
6 metadata JSONB DEFAULT '{}',
7 tags TEXT[] DEFAULT '{}',
8 created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
9);
10
11-- 创建GIN索引用于JSONB查询
12CREATE INDEX idx_products_metadata ON products USING GIN (metadata);
13
14-- JSONB查询示例
15SELECT * FROM products
16WHERE metadata @> '{"category": "electronics"}'
17AND tags && ARRAY['new', 'featured'];MongoDB
1// 插入文档
2db.users.insertMany([
3 {
4 username: "张三",
5 email: "zhangsan@example.com",
6 profile: {
7 age: 28,
8 city: "北京",
9 interests: ["编程", "阅读", "旅行"]
10 },
11 orders: [
12 { product_id: "prod_001", amount: 299.99, status: "completed" },
13 { product_id: "prod_002", amount: 599.99, status: "pending" }
14 ],
15 created_at: new Date()
16 },
17 {
18 username: "李四",
19 email: "lisi@example.com",
20 profile: {
21 age: 32,
22 city: "上海",
23 interests: ["摄影", "音乐"]
24 },
25 created_at: new Date()
26 }
27]);
28
29// 聚合查询
30db.users.aggregate([
31 { $match: { "profile.age": { $gte: 25 } } },
32 { $unwind: "$orders" },
33 { $group: {
34 _id: "$username",
35 total_spent: { $sum: "$orders.amount" },
36 order_count: { $sum: 1 }
37 }},
38 { $sort: { total_spent: -1 } }
39]);Redis
1# 字符串操作
2SET user:1001:name "张三"
3SET user:1001:email "zhangsan@example.com"
4EXPIRE user:1001:session 3600
5
6# 哈希操作
7HSET user:1001 profile:name "张三" profile:age 28 profile:city "北京"
8HGETALL user:1001
9
10# 列表操作(最新消息)
11LPUSH news:feed "用户张三发布了新文章"
12LTRIM news:feed 0 99 # 只保留最近100条
13
14# 集合操作(标签)
15SADD article:1001:tags "技术" "数据库" "Redis"
16SISMEMBER article:1001:tags "技术"
17
18# 有序集合(排行榜)
19ZADD leaderboard 1000 "player1" 850 "player2" 1200 "player3"
20ZREVRANGE leaderboard 0 9 WITHSCORESSQLite
1-- 创建内存数据库连接
2-- 创建表
3CREATE TABLE IF NOT EXISTS todos (
4 id INTEGER PRIMARY KEY AUTOINCREMENT,
5 title TEXT NOT NULL,
6 completed BOOLEAN DEFAULT 0,
7 priority INTEGER DEFAULT 1 CHECK (priority BETWEEN 1 AND 5),
8 due_date DATE,
9 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
10);
11
12-- 插入数据
13INSERT INTO todos (title, priority, due_date) VALUES
14('完成项目文档', 3, '2026-03-15'),
15('修复Bug #123', 5, '2026-03-10'),
16('代码审查', 2, NULL);
17
18-- 查询未完成的任务
19SELECT * FROM todos
20WHERE completed = 0
21ORDER BY priority DESC, due_date ASC;📃 标记语言
Markdown
1# 一级标题
2
3## 二级标题
4
5### 三级标题
6
7**粗体文本**
8
9*斜体文本*
10
11- 列表项 1
12- 列表项 2
13- 列表项 3
14
15> 引用块
16
17[链接文本](https://example.com)
18
19🔍 语言别名支持
以下别名都会被正确识别并显示相同图标:
| 语言 | 支持的别名 |
|---|---|
| JavaScript | js, javascript, jsx, mjs, cjs |
| TypeScript | ts, typescript, tsx, mts, cts |
| Vue | vue, vuejs |
| CSS | css, less, stylus |
| SCSS | scss, sass |
| HTML | html, htm, xhtml |
| Markdown | md, markdown, mdx |
| Python | python, py, py3, python3 |
| Go | go, golang |
| C | c, h |
| C# | csharp, c#, cs |
| Java | java |
| Rust | rust, rs |
| Kotlin | kotlin, kt, kts |
| PHP | php |
| Bash/Shell | bash, shell, sh, zsh |
| MySQL | mysql |
| PostgreSQL | postgresql, pgsql, postgres |
| MongoDB | mongodb, mongo |
| Redis | redis |
| SQLite | sqlite |
| SQL Server | sqlserver, mssql |
| MariaDB | mariadb |
| Elasticsearch | elasticsearch, es |
⚙️ 功能特点
✅ 自动识别
- 从代码块
class属性自动提取语言信息 - 支持
language-*和highlight-*前缀 - 支持
data-lang属性
✅ 大小写不敏感
1// 大写的 JS 也能识别
2const greeting = "Hello World";✅ 参数处理
1// 带参数的代码块也能正确识别
2function example() {
3 return "支持参数格式";
4}✅ 代码块标题
支持在 Markdown 代码块中使用 [] 语法添加标题:
语法格式
1```md [一级标题示例代码]
2# 一级标题
3```示例
1function processUser(user) {
2 const { name, age, email } = user;
3 return {
4 displayName: name.toUpperCase(),
5 isAdult: age >= 18,
6 contact: email.toLowerCase()
7 };
8}1def filter_data(data, threshold=100):
2 """过滤大于阈值的数据"""
3 return [item for item in data if item > threshold]
4
5# 使用示例
6numbers = [50, 150, 80, 200, 30]
7filtered = filter_data(numbers)
8print(filtered) # [150, 200] 1package main
2
3import (
4 "fmt"
5 "net/http"
6)
7
8func main() {
9 http.HandleFunc("/", handler)
10 fmt.Println("Server starting on :8080")
11 http.ListenAndServe(":8080", nil)
12}✅ 默认图标
对于未识别的语言,会显示默认的代码图标:
1这是未知语言的代码块
2会显示默认图标🎨 图标设计
所有图标均采用官方品牌颜色和设计风格:
- JavaScript - 黄色
#f7df1e - TypeScript - 蓝色
#3178c6 - Vue - 绿色
#42b883 - CSS - 蓝色
#264de4 - SCSS - 粉色
#cf649a - HTML - 橙色
#e34c26 - PHP - 紫色
#777bb4 - Python - 蓝黄双色
#3776ab/#ffd43b - Go - 青色
#00add8 - Java - 蓝橙双色
#007396/#f8981d - C - 蓝色
#00599c - C# - 紫色
#9b4f96 - Rust - 棕色
#dea584 - Kotlin - 紫色
#7f52ff - Markdown - 蓝色
#087ea4 - Bash/Shell - 绿色
#4eaa25 - MySQL - 蓝色
#4479a1 - PostgreSQL - 蓝色
#336791 - MongoDB - 绿色
#47a248 - Redis - 红色
#dc382d - SQLite - 深蓝
#003b57 - SQL Server - 红色
#a91d22 - MariaDB - 深灰
#003545 - Elasticsearch - 黄色
#fec514
🚀 性能优化
- 使用
Intersection Observer实现懒加载 - 使用
MutationObserver监听动态添加的代码块 - 图标缓存避免重复渲染
- 仅显示图标,不显示语言名称,界面更简洁
📡
👤
作者:
余温Gueen
🌐
版权:
本站文章除特别声明外,均采用
CC BY-NC-SA 4.0
协议,转载请注明来自
余温Gueen Blog!
推荐使用微信支付

推荐使用支付宝
