This commit is contained in:
@@ -6,50 +6,55 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm" // <-- 确保导入 gorm
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func Home(c *gin.Context) {
|
||||
// getThemeManager 从上下文中获取主题管理器
|
||||
func getThemeManager(c *gin.Context) (*utils.ThemeManager, bool) {
|
||||
tm, exists := c.Get("ThemeManager")
|
||||
if !exists {
|
||||
c.String(http.StatusInternalServerError, "Theme manager not found in context")
|
||||
return
|
||||
return nil, false
|
||||
}
|
||||
themeManager, ok := tm.(*utils.ThemeManager)
|
||||
return themeManager, ok
|
||||
}
|
||||
|
||||
// getDB 从上下文中获取数据库实例
|
||||
func getDB(c *gin.Context) (*gorm.DB, bool) {
|
||||
dbInterface, exists := c.Get("DB")
|
||||
if !exists {
|
||||
return nil, false
|
||||
}
|
||||
db, ok := dbInterface.(*gorm.DB)
|
||||
return db, ok
|
||||
}
|
||||
|
||||
// Home 首页
|
||||
func Home(c *gin.Context) {
|
||||
themeManager, ok := getThemeManager(c)
|
||||
if !ok {
|
||||
c.String(http.StatusInternalServerError, "Invalid theme manager type in context")
|
||||
c.String(http.StatusInternalServerError, "Theme manager not found")
|
||||
return
|
||||
}
|
||||
|
||||
db, ok := getDB(c)
|
||||
if !ok {
|
||||
c.String(http.StatusInternalServerError, "DB not found")
|
||||
return
|
||||
}
|
||||
|
||||
var items []models.Content
|
||||
// 从 Gin 上下文中获取 DB 实例
|
||||
dbInterface, exists := c.Get("DB")
|
||||
if !exists {
|
||||
c.String(http.StatusInternalServerError, "DB not found in context")
|
||||
return
|
||||
}
|
||||
db, ok := dbInterface.(*gorm.DB)
|
||||
if !ok {
|
||||
c.String(http.StatusInternalServerError, "Invalid DB type in context")
|
||||
return
|
||||
}
|
||||
|
||||
db.Select("*").Limit(5).Find(&items, "type = ?", "post")
|
||||
|
||||
tpl := themeManager.GetTemplate("index") // "index" 是模板的基本名 (例如 index.tmpl -> index)
|
||||
tpl := themeManager.GetTemplate("index")
|
||||
if tpl == nil {
|
||||
c.String(http.StatusInternalServerError, "Template 'index' not found in current theme: "+themeManager.CurrentTheme())
|
||||
c.String(http.StatusInternalServerError, "Template 'index' not found")
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusOK)
|
||||
c.Header("Content-Type", "text/html; charset=utf-8")
|
||||
err := tpl.Execute(c.Writer, gin.H{
|
||||
tpl.Execute(c.Writer, gin.H{
|
||||
"Items": items,
|
||||
"Title": "首页", // 你可以根据需要传递更多数据
|
||||
"Title": "首页",
|
||||
})
|
||||
if err != nil {
|
||||
// 实际项目中应记录错误
|
||||
c.String(http.StatusInternalServerError, "Error rendering template: "+err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user