Files
go_blog/controllers/themes.go

88 lines
2.5 KiB
Go
Raw Normal View History

2025-05-27 19:01:05 +08:00
package controllers
import (
2025-06-18 18:34:08 +08:00
"html/template"
2025-06-09 17:59:19 +08:00
"net/http"
"go_blog/config"
2025-05-27 19:01:05 +08:00
"go_blog/themes"
"github.com/gin-gonic/gin"
)
2025-06-09 17:59:19 +08:00
// ListThemes 显示主题管理页面(返回主题列表和当前主题)
2025-05-27 19:01:05 +08:00
func ListThemes(c *gin.Context) {
2025-06-09 17:59:19 +08:00
// 从上下文中获取主题管理器
2025-05-27 19:01:05 +08:00
tm, exists := c.Get("ThemeManager")
if !exists {
2025-06-09 17:59:19 +08:00
c.String(http.StatusInternalServerError, "主题管理器未找到")
return
}
themeManager, ok := tm.(*themes.ThemeManager)
if !ok {
c.String(http.StatusInternalServerError, "主题管理器类型错误")
2025-05-27 19:01:05 +08:00
return
}
2025-06-09 17:59:19 +08:00
// 获取可用主题列表(读取 web/themes 目录下的所有子目录)
entries, err := themeManager.GetAvailableThemes() // 假设 ThemeManager 新增获取主题列表方法
2025-05-27 19:01:05 +08:00
if err != nil {
2025-06-09 17:59:19 +08:00
c.String(http.StatusInternalServerError, "读取主题目录失败: "+err.Error())
2025-05-27 19:01:05 +08:00
return
}
2025-06-09 17:59:19 +08:00
// 渲染管理页面模板
2025-06-18 18:34:08 +08:00
// 直接加载 web/admin/themes.tmpl 文件(路径相对于项目根目录)
const themesTemplatePath = "web/admin/themes.tmpl" // 定义模板路径常量
tpl, err := template.ParseFiles(themesTemplatePath)
if err != nil {
c.String(http.StatusInternalServerError, "模板加载失败: "+err.Error())
2025-06-09 17:59:19 +08:00
return
2025-05-27 19:01:05 +08:00
}
2025-06-09 17:59:19 +08:00
c.Header("Content-Type", "text/html; charset=utf-8")
err = tpl.Execute(c.Writer, gin.H{
"CurrentTheme": themeManager.CurrentTheme(),
"Themes": entries,
2025-05-27 19:01:05 +08:00
})
2025-06-09 17:59:19 +08:00
if err != nil {
c.String(http.StatusInternalServerError, "渲染模板失败: "+err.Error())
}
}
// SwitchTheme 处理主题切换请求
func SwitchTheme(c *gin.Context) {
// 从上下文中获取主题管理器
tm, exists := c.Get("ThemeManager")
if !exists {
c.JSON(http.StatusInternalServerError, gin.H{"error": "主题管理器未找到"})
return
}
themeManager, ok := tm.(*themes.ThemeManager)
if !ok {
c.JSON(http.StatusInternalServerError, gin.H{"error": "主题管理器类型错误"})
return
}
// 获取前端提交的主题名称
newTheme := c.PostForm("theme")
if newTheme == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "主题名称不能为空"})
return
}
// 加载新主题
if err := themeManager.LoadTheme(newTheme); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "加载主题失败: " + err.Error()})
return
}
// 持久化主题配置(假设 config 包支持保存到配置文件)
if err := config.SetCurrentTheme(newTheme); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "保存主题配置失败: " + err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "主题切换成功", "current_theme": newTheme})
2025-05-27 19:01:05 +08:00
}