主题开发

主题系统入门

RyeBlog 发布于 2026-11-15 约 2.2 千字
主题系统入门

主题系统入门

RyeBlog 的主题系统基于 SSR 渲染函数和 CSS 变量。没有模板引擎,没有 JSX,只有纯 JavaScript 函数和 CSS。

核心理念

RyeBlog 的主题系统遵循一个原则:简单到任何人都能改。

  • 没有 Handlebars/EJS/Pug 等模板引擎
  • 没有 React/Vue 等组件框架
  • 没有 Webpack/Vite 等构建工具
  • 只有 JavaScript 函数 生成 HTML 字符串 + CSS 文件 控制样式

模板结构

渲染函数(lib/render.js)

所有页面渲染都在 lib/render.js 中:

// 页面外壳(所有页面共用)
export function renderPage(options, data) {
  const { title, content } = options;
  return <!DOCTYPE html>
<html lang="zh-CN">
<head>
  <title>${title}</title>
  <link rel="stylesheet" href="/style.css">
</head>
<body>
  <header>...</header>
  <div id="app">${content}</div>
  <footer>...</footer>
</body>
</html>;
}

// 首页内容
export function buildHomepageContent(articles, categories, tags, settings) {
return <div class="layout-wrapper">
<main class="main-content">
${articles.map(a => renderArticleItem(a, categories)).join('')}
</main>
<aside class="sidebar-right">...</aside>
</div>
;
}

// 文章详情页内容
export function buildArticleContent(article, categories, tags, settings) {
return <article class="article-detail">
<h1>${article.title_zh}</h1>
<div class="article-content">${parseMarkdown(article.content_zh)}</div>
</article>
;
}

CSS(public/style.css)

所有样式在一个 CSS 文件中,使用 CSS 变量定义主题色:

:root {
  --bg: #faf8f3;
  --text: #2c2c2c;
  --accent: #c4554d;
  --accent-light: #f5e6e3;
  --border: #e8e4dc;
  --font-serif: 'Noto Serif SC', Georgia, serif;
  --font-sans: -apple-system, 'Segoe UI', sans-serif;
}

如何定制主题

1. 改配色

修改 CSS 变量即可改变全站配色:

:root {
  --bg: #1a1a2e;        /* 深色背景 */
  --text: #e0e0e0;      /* 浅色文字 */
  --accent: #e94560;    /* 亮色强调 */
  --accent-light: #16213e;
  --border: #0f3460;
}

2. 改字体

:root {
  --font-serif: 'Lora', Georgia, serif;
  --font-sans: 'Inter', -apple-system, sans-serif;
}

在 HTML 中引入 Google Fonts:

<link href="https://fonts.googleapis.com/css2?family=Lora&family=Inter&display=swap" rel="stylesheet">

3. 改布局

修改 renderPage 函数中的 HTML 结构,或修改 CSS 中的布局属性:

.layout-wrapper {
  display: grid;
  grid-template-columns: 1fr 300px;  /* 改为单列:1fr */
  gap: 2rem;
}

4. 添加新页面

  • 在 functions/ 中创建新路由文件
  • 在 lib/render.js 中添加对应的渲染函数
  • 在 CSS 中添加对应样式

CSS 变量系统

RyeBlog 的所有视觉属性都通过 CSS 变量控制,修改变量即可改变全站风格:

变量作用默认值
--bg页面背景#faf8f3
--text正文文字#2c2c2c
--accent强调色#c4554d
--accent-light强调色浅色#f5e6e3
--border边框色#e8e4dc
--font-serif衬线字体'Noto Serif SC', Georgia, serif
--font-sans无衬线字体-apple-system, 'Segoe UI', sans-serif
--content-width内容区宽度720px
--sidebar-width侧边栏宽度300px

深色模式

RyeBlog 内置深色模式,通过 data-theme 属性切换:

:root[data-theme="dark"] {
  --bg: #1a1a2e;
  --text: #e0e0e0;
  --accent: #e94560;
  --accent-light: #16213e;
  --border: #0f3460;
}

切换按钮在 renderPage 中已经内置,用户点击即可切换,选择保存在 localStorage。',