46 lines
1.4 KiB
Go
46 lines
1.4 KiB
Go
package themes // Declare the package at the top
|
|
|
|
import (
|
|
"fmt"
|
|
config "go_blog/config" // Adjust import path as needed
|
|
"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
|
|
// SwitchTheme 处理主题切换请求(修正后)
|
|
func SwitchTheme(c *gin.Context) {
|
|
// 从上下文中获取主题管理器(通过 main.go 的 themeMiddleware 注入)
|
|
tm, exists := c.Get("ThemeManager")
|
|
if !exists {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "主题管理器未找到"})
|
|
return
|
|
}
|
|
themeManager, ok := tm.(*ThemeManager)
|
|
if !ok {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "主题管理器类型错误"})
|
|
return
|
|
}
|
|
|
|
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": "主题切换成功"})
|
|
}
|