🌟 功能简介

为了方便记录平时零碎的代码片段和小知识点,我们专门构建了一个“代码片段”页面。该功能特点包括:

  1. 卡片式布局:采用 CSS Grid 实现响应式瀑布流效果。
  2. 数据化驱动:通过 YAML 文件管理内容,无需频繁修改 HTML。
  3. 样式统一:延续全站的毛玻璃质感与深色模式适配。

🛠️ 配置步骤

1. 准备数据文件

source/_data/ 目录下创建 snippets.yml

1
2
3
4
5
6
- title: "示例片段"
tags: ["标签1", "标签2"]
content: |
这里写你的代码或知识点,支持 Markdown 格式。
```javascript
console.log('Hello World');

date: “2026-02-12”

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

### 2. 创建页面模板

在 `themes/butterfly/layout/includes/page/` 目录下创建 `snippets.pug`:

```pug
#article-container
if site.data.snippets
.snippets-container
each item in site.data.snippets
.snippet-item
.snippet-header
if item.title
span.snippet-title= item.title
if item.date
span.snippet-date
i.far.fa-calendar-alt
span= item.date
.snippet-content
!= markdown(item.content)
if item.tags
.snippet-footer
each tag in item.tags
span.snippet-tag
i.fas.fa-tag
span= tag
else
p 暂无代码片段

3. 注册页面类型

修改 themes/butterfly/layout/page.pug,在 case page.type 中添加:

1
2
when 'snippets'
include includes/page/snippets.pug

同时在文件顶部的 noCardLayout 数组中添加 'snippets' 以获得更自由的布局:

1
- const noCardLayout = ['shuoshuo', 'snippets', '404'].includes(page.type) ? 'nc' : ''

4. 添加分页逻辑 (核心更新)

为了防止片段过多导致页面加载缓慢,我们在 snippets.pug 中引入了与“即刻”类似的 client-side 分页逻辑。

snippets.pug 中添加以下 JavaScript 逻辑:

1
2
3
4
script(type='application/json' id='snippets-data')!= safeJSON(site.data.snippets)
script.
// ... 分页核心逻辑 ...
// 包括 renderData, renderNavigation, renderPage 等函数

5. 添加 CSS 样式

source/css/custom.css 中添加代码片段专属样式(包含瀑布流网格和卡片美化):

1
2
3
4
5
6
7
8
9
10
11
12
.snippets-container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
gap: 20px;
}
.snippet-item {
background: rgba(255, 255, 255, 0.7);
backdrop-filter: blur(10px);
border-radius: 12px;
padding: 20px;
/* ... 更多样式见 custom.css ... */
}

5. 创建 Markdown 页面

执行命令创建页面:
hexo new page snippets

然后在 source/snippets/index.md 中设置:

1
2
3
4
5
---
title: 代码片段
type: "snippets"
aside: false
---

📝 维护说明

今后若要新增代码片段,只需在 source/_data/snippets.yml 中按照格式追加内容即可,页面会自动同步更新。