This commit is contained in:
张超
2025-05-27 19:01:05 +08:00
parent f02495cc7a
commit 5ffc64e1dd
16 changed files with 512 additions and 123 deletions

View File

@@ -39,6 +39,12 @@ func NewManager(themesDir string) *ThemeManager {
}
}
// 自定义错误类型
var (
ErrInvalidThemeStructure = errors.New("invalid theme structure")
ErrNoValidTemplates = errors.New("no valid templates found")
)
// 核心方法:加载主题
func (m *ThemeManager) LoadTheme(themeName string) error {
m.mu.Lock()
@@ -47,7 +53,7 @@ func (m *ThemeManager) LoadTheme(themeName string) error {
// 1. 验证主题目录结构
themePath := filepath.Join(m.themesDir, themeName)
if !isValidTheme(themePath) {
return fmt.Errorf("invalid theme structure: %s", themeName)
return fmt.Errorf("%w: %s", ErrInvalidThemeStructure, themeName)
}
// 2. 加载模板文件
@@ -85,21 +91,50 @@ func (m *ThemeManager) RegisterStaticRoutes(router *gin.Engine) {
// 校验主题完整性
func isValidTheme(themePath string) bool {
requiredFiles := []string{
requiredBaseFiles := []string{ // 不带扩展名的基本文件名
"theme.yaml",
// "templates/home.html",
// "templates/post.html",
"templates/index.html",
"templates/index", // 例如: templates/index.html 或 templates/index.tmpl
// "templates/post", // 如果 post 模板是必须的,也加入这里
}
supportedTemplateExtensions := []string{".html", ".tmpl"}
for _, f := range requiredFiles {
if _, err := os.Stat(filepath.Join(themePath, f)); os.IsNotExist(err) {
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
}
}
if !found {
// log.Printf("Required file/template %s not found in theme %s", baseFile, themePath) // 可选的调试日志
return false
}
}
return true
}
// 检查文件是否存在
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
}
// 解析模板文件(支持布局继承)
func (m *ThemeManager) parseTemplates(themePath string) (map[string]*template.Template, error) {
templates := make(map[string]*template.Template)
@@ -112,25 +147,37 @@ func (m *ThemeManager) parseTemplates(themePath string) (map[string]*template.Te
// 从主题目录加载模板
tplDir := filepath.Join(themePath, "templates")
err := filepath.WalkDir(tplDir, func(path string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() || !strings.HasSuffix(path, ".html") {
return nil
if err != nil {
return err // 返回错误以停止 WalkDir
}
if d.IsDir() {
return nil // 跳过目录
}
// 支持 .html 和 .tmpl 扩展名
lowerPath := strings.ToLower(path)
if !strings.HasSuffix(lowerPath, ".html") && !strings.HasSuffix(lowerPath, ".tmpl") {
return nil // 非模板文件,跳过
}
// 读取模板内容
content, err := os.ReadFile(path)
content, err := readFile(path)
if err != nil {
return err
return fmt.Errorf("failed to read template file %s: %w", path, err)
}
// 生成模板名称(相对路径)
// 生成模板名称(相对路径,不含扩展名
name := strings.TrimPrefix(path, tplDir+string(filepath.Separator))
name = strings.TrimSuffix(name, filepath.Ext(name))
// 克隆基础模板并解析
tpl := template.Must(baseTpl.Clone())
tpl, err := baseTpl.Clone()
if err != nil {
return fmt.Errorf("failed to clone base template for %s: %w", name, err)
}
tpl, err = tpl.Parse(string(content))
if err != nil {
return fmt.Errorf("parse error in %s: %w", name, err)
return fmt.Errorf("parse error in %s (file: %s): %w", name, path, err)
}
templates[name] = tpl
@@ -142,12 +189,17 @@ func (m *ThemeManager) parseTemplates(themePath string) (map[string]*template.Te
}
if len(templates) == 0 {
return nil, errors.New("no valid templates found")
return nil, ErrNoValidTemplates
}
return templates, nil
}
// 读取文件内容
func readFile(path string) ([]byte, error) {
return os.ReadFile(path)
}
// 获取可用主题列表
func (m *ThemeManager) ListThemes() ([]string, error) {
dirs, err := os.ReadDir(m.themesDir)