Files
go_blog/themes/manager.go
2025-04-15 16:47:00 +08:00

58 lines
1.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package themes // Declare the package at the top
import (
"fmt"
"html/template"
"net/http"
"os"
"path/filepath"
"strings"
)
// ThemeManager manages themes for the blog system
type ThemeManager struct {
CurrentTheme string // Name of the currently active theme
Templates map[string]*template.Template // Cached compiled HTML templates
}
// LoadTheme loads a specified theme by its name
func (tm *ThemeManager) LoadTheme(themeName string) error {
// 1. 读取theme.yaml验证主题有效性
// 2. 预编译所有HTML模板缓存到Templates
// 3. 注册静态资源路由:/themes/[name]/static/*filepath
tm.CurrentTheme = themeName
// Step 1: Validate the theme by reading theme.yaml
themeConfigPath := fmt.Sprintf("h:/code/go_blog/web/themes/%s/theme.yaml", themeName)
if _, err := os.Stat(themeConfigPath); os.IsNotExist(err) {
return fmt.Errorf("theme %s does not exist or is invalid", themeName)
}
// Step 2: Precompile all HTML templates and cache them
tm.Templates = make(map[string]*template.Template)
templateDir := fmt.Sprintf("h:/code/go_blog/web/themes/%s/tmplates/", themeName)
err := filepath.Walk(templateDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && strings.HasSuffix(info.Name(), ".tmpl") {
tmpl, err := template.ParseFiles(path)
if err != nil {
return err
}
tm.Templates[info.Name()] = tmpl
}
return nil
})
if err != nil {
return fmt.Errorf("failed to load templates: %v", err)
}
// Step 3: Register static resource routes
http.Handle(fmt.Sprintf("/themes/%s/static/", themeName), http.StripPrefix(fmt.Sprintf("/themes/%s/static/", themeName), http.FileServer(http.Dir(fmt.Sprintf("h:/code/go_blog/themes/%s/static", themeName)))))
return nil
}
func NewManager() *ThemeManager {
return &ThemeManager{}
}