update
This commit is contained in:
@@ -2,16 +2,54 @@ package controllers
|
||||
|
||||
import (
|
||||
"go_blog/models"
|
||||
"go_blog/themes" // <-- 确保导入 themes 包
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm" // <-- 确保导入 gorm
|
||||
)
|
||||
|
||||
func Home(c *gin.Context) {
|
||||
tm, exists := c.Get("ThemeManager")
|
||||
if !exists {
|
||||
c.String(http.StatusInternalServerError, "Theme manager not found in context")
|
||||
return
|
||||
}
|
||||
themeManager, ok := tm.(*themes.ThemeManager)
|
||||
if !ok {
|
||||
c.String(http.StatusInternalServerError, "Invalid theme manager type in context")
|
||||
return
|
||||
}
|
||||
|
||||
var items []models.Content
|
||||
models.DB.Select("*").Limit(5).Find(&items, "type = ?", "post")
|
||||
c.HTML(http.StatusOK, "index.tmpl", gin.H{
|
||||
// 从 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)
|
||||
if tpl == nil {
|
||||
c.String(http.StatusInternalServerError, "Template 'index' not found in current theme: "+themeManager.CurrentTheme())
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusOK)
|
||||
c.Header("Content-Type", "text/html; charset=utf-8")
|
||||
err := tpl.Execute(c.Writer, gin.H{
|
||||
"Items": items,
|
||||
"Title": "首页", // 你可以根据需要传递更多数据
|
||||
})
|
||||
if err != nil {
|
||||
// 实际项目中应记录错误
|
||||
c.String(http.StatusInternalServerError, "Error rendering template: "+err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user