Files
go_blog/utils/thememanager.go

264 lines
6.6 KiB
Go
Raw Permalink Normal View History

2025-07-12 15:56:36 +08:00
package utils
2025-05-21 20:38:25 +08:00
2025-04-01 17:59:10 +08:00
import (
2025-05-22 13:57:45 +08:00
"embed"
2025-05-21 20:38:25 +08:00
"errors"
2025-04-01 17:59:10 +08:00
"fmt"
"html/template"
2025-05-21 20:38:25 +08:00
"io/fs"
2025-04-01 17:59:10 +08:00
"os"
"path/filepath"
"strings"
2025-05-21 20:38:25 +08:00
"sync"
"github.com/gin-gonic/gin"
2025-04-01 17:59:10 +08:00
)
2025-05-22 13:57:45 +08:00
// 主题元数据结构
2025-05-21 20:38:25 +08:00
type ThemeMeta struct {
Name string `yaml:"name"`
2025-05-22 13:56:57 +08:00
Author string `yaml:"author"`
2025-05-22 13:57:45 +08:00
Version string `yaml:"version"`
2025-05-21 20:38:25 +08:00
Description string `yaml:"description"`
}
2025-05-22 13:57:45 +08:00
// 主题管理器
2025-04-01 17:59:10 +08:00
type ThemeManager struct {
2025-05-22 13:57:45 +08:00
mu sync.RWMutex
currentTheme string
templates map[string]*template.Template
baseTemplates embed.FS // 可选:嵌入基础模板
themesDir string
2025-05-21 20:38:25 +08:00
}
2025-05-22 13:57:45 +08:00
// 创建新主题管理器
func NewManager(themesDir string) *ThemeManager {
return &ThemeManager{
templates: make(map[string]*template.Template),
2025-05-21 20:38:25 +08:00
themesDir: themesDir,
}
}
2025-05-27 19:01:05 +08:00
// 自定义错误类型
var (
ErrInvalidThemeStructure = errors.New("invalid theme structure")
ErrNoValidTemplates = errors.New("no valid templates found")
)
2025-05-22 13:57:45 +08:00
// 核心方法:加载主题
func (themeManager *ThemeManager) LoadTheme(themeName string) error {
themeManager.mu.Lock()
defer themeManager.mu.Unlock()
2025-05-22 13:56:57 +08:00
2025-05-22 13:57:45 +08:00
// 1. 验证主题目录结构
themePath := filepath.Join(themeManager.themesDir, themeName)
2025-05-22 13:57:45 +08:00
if !isValidTheme(themePath) {
2025-05-27 19:01:05 +08:00
return fmt.Errorf("%w: %s", ErrInvalidThemeStructure, themeName)
2025-05-21 20:38:25 +08:00
}
2025-05-22 13:57:45 +08:00
// 2. 加载模板文件
tpls, err := themeManager.parseTemplates(themePath)
2025-05-21 20:38:25 +08:00
if err != nil {
2025-05-22 13:57:45 +08:00
return fmt.Errorf("template parsing failed: %w", err)
2025-05-21 20:38:25 +08:00
}
2025-05-22 13:57:45 +08:00
// 3. 更新当前主题
themeManager.currentTheme = themeName
themeManager.templates = tpls
2025-05-22 13:57:45 +08:00
return nil
}
2025-05-21 20:38:25 +08:00
2025-05-22 13:57:45 +08:00
// 获取当前主题名称
func (m *ThemeManager) CurrentTheme() string {
m.mu.RLock()
defer m.mu.RUnlock()
return m.currentTheme
}
2025-05-21 20:38:25 +08:00
2025-05-22 13:57:45 +08:00
// 获取编译后的模板
func (m *ThemeManager) GetTemplate(name string) *template.Template {
m.mu.RLock()
defer m.mu.RUnlock()
return m.templates[name]
}
2025-05-21 20:38:25 +08:00
2025-05-22 13:57:45 +08:00
// 注册静态文件路由Gin框架
func (m *ThemeManager) RegisterStaticRoutes(router *gin.Engine) {
staticPath := filepath.Join(m.themesDir, m.currentTheme, "static")
router.StaticFS("/theme/static", gin.Dir(staticPath, false))
2025-04-01 17:59:10 +08:00
}
2025-05-22 13:57:45 +08:00
// 校验主题完整性
func isValidTheme(themePath string) bool {
2025-05-27 19:01:05 +08:00
requiredBaseFiles := []string{ // 不带扩展名的基本文件名
2025-05-22 13:57:45 +08:00
"theme.yaml",
2025-05-27 19:01:05 +08:00
"templates/index", // 例如: templates/index.html 或 templates/index.tmpl
// "templates/post", // 如果 post 模板是必须的,也加入这里
2025-05-21 20:38:25 +08:00
}
2025-05-27 19:01:05 +08:00
supportedTemplateExtensions := []string{".html", ".tmpl"}
for _, baseFile := range requiredBaseFiles {
found := false
if strings.HasPrefix(baseFile, "templates/") {
// 对于模板文件,尝试所有支持的扩展名
for _, ext := range supportedTemplateExtensions {
if exists, _ := fileExists(filepath.Join(themePath, baseFile+ext)); exists {
found = true
break
}
}
} else {
// 对于非模板文件 (如 theme.yaml),直接检查
if exists, _ := fileExists(filepath.Join(themePath, baseFile)); exists {
found = true
}
}
2025-04-01 17:59:10 +08:00
2025-05-27 19:01:05 +08:00
if !found {
// log.Printf("Required file/template %s not found in theme %s", baseFile, themePath) // 可选的调试日志
2025-05-22 13:57:45 +08:00
return false
2025-05-21 20:38:25 +08:00
}
2025-04-01 17:59:10 +08:00
}
2025-05-22 13:57:45 +08:00
return true
2025-05-21 20:38:25 +08:00
}
2025-05-27 19:01:05 +08:00
// 检查文件是否存在
func fileExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
2025-05-22 13:57:45 +08:00
// 解析模板文件(支持布局继承)
func (m *ThemeManager) parseTemplates(themePath string) (map[string]*template.Template, error) {
templates := make(map[string]*template.Template)
2025-04-01 17:59:10 +08:00
2025-05-22 13:57:45 +08:00
// 从主题目录加载模板
2025-05-21 20:38:25 +08:00
tplDir := filepath.Join(themePath, "templates")
2026-02-12 15:45:11 +08:00
// 首先读取所有模板文件内容
type tplFile struct {
name string
path string
content []byte
}
var tplFiles []tplFile
2025-05-22 13:57:45 +08:00
err := filepath.WalkDir(tplDir, func(path string, d fs.DirEntry, err error) error {
2025-05-27 19:01:05 +08:00
if err != nil {
2026-02-12 15:45:11 +08:00
return err
2025-05-27 19:01:05 +08:00
}
if d.IsDir() {
2026-02-12 15:45:11 +08:00
return nil
2025-05-27 19:01:05 +08:00
}
// 支持 .html 和 .tmpl 扩展名
lowerPath := strings.ToLower(path)
if !strings.HasSuffix(lowerPath, ".html") && !strings.HasSuffix(lowerPath, ".tmpl") {
2026-02-12 15:45:11 +08:00
return nil
2025-05-21 20:38:25 +08:00
}
2025-05-27 19:01:05 +08:00
content, err := readFile(path)
2025-05-22 13:57:45 +08:00
if err != nil {
2025-05-27 19:01:05 +08:00
return fmt.Errorf("failed to read template file %s: %w", path, err)
2025-04-01 17:59:10 +08:00
}
2025-05-21 20:38:25 +08:00
2025-05-22 13:57:45 +08:00
name := strings.TrimPrefix(path, tplDir+string(filepath.Separator))
name = strings.TrimSuffix(name, filepath.Ext(name))
2025-05-21 20:38:25 +08:00
2026-02-12 15:45:11 +08:00
tplFiles = append(tplFiles, tplFile{name: name, path: path, content: content})
2025-04-01 17:59:10 +08:00
return nil
})
2025-05-21 20:38:25 +08:00
2025-05-22 13:57:45 +08:00
if err != nil {
return nil, err
}
2025-05-22 13:56:57 +08:00
2026-02-12 15:45:11 +08:00
if len(tplFiles) == 0 {
2025-05-27 19:01:05 +08:00
return nil, ErrNoValidTemplates
2025-05-22 13:57:45 +08:00
}
2025-04-01 17:59:10 +08:00
2026-02-12 15:45:11 +08:00
// 创建包含所有模板的根模板
funcMap := template.FuncMap{
"safeHTML": func(s string) template.HTML { return template.HTML(s) },
}
// 首先解析基础模板base.tmpl 和 header.tmpl
var baseContent strings.Builder
for _, tf := range tplFiles {
if tf.name == "base" || tf.name == "header" {
baseContent.WriteString(string(tf.content))
baseContent.WriteString("\n")
}
}
rootTpl, err := template.New("root").Funcs(funcMap).Parse(baseContent.String())
if err != nil {
return nil, fmt.Errorf("failed to parse base templates: %w", err)
}
// 为每个页面模板单独解析,继承基础模板
for _, tf := range tplFiles {
// 跳过基础模板,它们已经在 rootTpl 中
if tf.name == "base" || tf.name == "header" {
templates[tf.name] = rootTpl
continue
}
// 克隆基础模板并添加页面特定内容
tpl, err := rootTpl.Clone()
if err != nil {
return nil, fmt.Errorf("failed to clone base template for %s: %w", tf.name, err)
}
// 解析页面特定内容,使用页面名称作为 define 名称
pageContent := string(tf.content)
_, err = tpl.Parse(pageContent)
if err != nil {
return nil, fmt.Errorf("failed to parse template %s: %w", tf.name, err)
}
templates[tf.name] = tpl
}
2025-05-22 13:57:45 +08:00
return templates, nil
2025-04-01 17:59:10 +08:00
}
2025-05-21 20:38:25 +08:00
2025-05-27 19:01:05 +08:00
// 读取文件内容
func readFile(path string) ([]byte, error) {
return os.ReadFile(path)
}
2025-06-09 17:59:19 +08:00
// GetAvailableThemes 获取所有可用主题(读取 themesDir 目录下的子目录)
func (m *ThemeManager) GetAvailableThemes() ([]string, error) {
entries, err := os.ReadDir(m.themesDir)
if err != nil {
return nil, fmt.Errorf("读取主题目录失败: %w", err)
}
2025-05-21 20:38:25 +08:00
var themes []string
2025-06-09 17:59:19 +08:00
for _, entry := range entries {
if entry.IsDir() {
themes = append(themes, entry.Name())
2025-05-21 20:38:25 +08:00
}
}
return themes, nil
2025-04-09 16:56:05 +08:00
}
// 加载主题下所有模板(包括子模板)
func (tm *ThemeManager) LoadTemplates(themeName string) error {
themePath := filepath.Join("web", "themes", themeName, "templates")
// 使用通配符加载所有tmpl文件
tmpl, err := template.ParseGlob(filepath.Join(themePath, "*.tmpl"))
if err != nil {
return fmt.Errorf("加载主题模板失败: %w", err)
}
tm.templates[themeName] = tmpl
return nil
}