Files
go_blog/themes/parser.go

46 lines
1.5 KiB
Go
Raw Normal View History

2025-04-09 16:56:05 +08:00
package themes // Declare the package at the top
2025-04-01 17:59:10 +08:00
import (
"fmt"
2025-04-09 16:56:05 +08:00
config "go_blog/config" // Adjust import path as needed
2025-04-01 17:59:10 +08:00
"net/http"
"github.com/gin-gonic/gin"
)
// RenderTemplate renders a template based on the current theme
func RenderTemplate(c *gin.Context, tmpl string, data gin.H) {
// Get the current theme
theme := config.GetCurrentTheme()
// Construct the template path: "themes/default/home.html"
tplPath := fmt.Sprintf("themes/%s/%s", theme, tmpl)
// Render the template using html/template
c.HTML(http.StatusOK, tplPath, data)
}
// SwitchTheme handles POST requests to switch the current theme
2025-05-27 19:01:05 +08:00
// SwitchTheme 处理主题切换请求(修正后)
2025-04-01 17:59:10 +08:00
func SwitchTheme(c *gin.Context) {
2025-05-27 19:01:05 +08:00
// 从上下文中获取主题管理器(通过 main.go 的 themeMiddleware 注入)
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
}
2025-04-01 17:59:10 +08:00
2025-05-27 19:01:05 +08:00
newTheme := c.PostForm("theme")
if err := themeManager.LoadTheme(newTheme); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "加载主题失败: " + err.Error()})
return
}
config.SetCurrentTheme(newTheme) // 持久化主题配置(需确保 config 包支持)
c.JSON(http.StatusOK, gin.H{"status": "主题切换成功"})
2025-04-01 17:59:10 +08:00
}