--
:
--
:
--
代码块语法
最后更新于:
🔤 代码块语言图标功能
本主题支持自动识别代码块语言并显示对应的官方品牌图标,提升代码可读性和视觉体验。
🎯 支持的编程语言
🌐 前端开发
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}🛠️ 系统编程
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}📝 标记语言
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 |
⚙️ 功能特点
✅ 自动识别
- 从代码块
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
🚀 性能优化
- 使用
Intersection Observer实现懒加载 - 使用
MutationObserver监听动态添加的代码块 - 图标缓存避免重复渲染
- 仅显示图标,不显示语言名称,界面更简洁
📡
👤
作者:
余温Gueen
🌐
版权:
本站文章除特别声明外,均采用
CC BY-NC-SA 4.0
协议,转载请注明来自
余温Gueen Blog!
推荐使用微信支付

推荐使用支付宝

- 01代码块语法 2026-02-27
- 02一个PHP的图片API 2026-02-11
- 03Hugo-Teek 小白首选,一款简约、唯美、丝滑且强大的博客和文档库二合一 2025-11-27