update
This commit is contained in:
@@ -2,19 +2,69 @@ package controllers
|
||||
|
||||
import (
|
||||
"go_blog/models"
|
||||
"go_blog/themes" // <-- 确保导入 themes 包
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm" // <-- 确保导入 gorm
|
||||
)
|
||||
|
||||
func ShowPost(c *gin.Context) {
|
||||
|
||||
id, err := strconv.ParseInt(c.Param("id"), 10, 32)
|
||||
if err != nil {
|
||||
tm, exists := c.Get("ThemeManager")
|
||||
if !exists {
|
||||
c.String(http.StatusInternalServerError, "Theme manager not found")
|
||||
return
|
||||
}
|
||||
themeManager, ok := tm.(*themes.ThemeManager)
|
||||
if !ok {
|
||||
c.String(http.StatusInternalServerError, "Invalid theme manager type")
|
||||
return
|
||||
}
|
||||
|
||||
idParam := c.Param("id")
|
||||
id, err := strconv.ParseInt(idParam, 10, 32)
|
||||
if err != nil {
|
||||
c.String(http.StatusBadRequest, "Invalid post ID format")
|
||||
return
|
||||
}
|
||||
|
||||
var content = models.Content{Cid: int32(id)}
|
||||
models.DB.First(&content)
|
||||
c.HTML(http.StatusOK, "post.tmpl", 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
|
||||
}
|
||||
|
||||
result := db.First(&content)
|
||||
if result.Error != nil {
|
||||
if result.Error == gorm.ErrRecordNotFound {
|
||||
c.String(http.StatusNotFound, "Post not found")
|
||||
} else {
|
||||
c.String(http.StatusInternalServerError, "Error fetching post: "+result.Error.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 假设你的主题中有一个名为 "post" 的模板 (post.html 或 post.tmpl)
|
||||
// 注意:当前的 default 主题 (web/themes/default/templates/) 并没有 post.tmpl,你需要添加它。
|
||||
tpl := themeManager.GetTemplate("post")
|
||||
if tpl == nil {
|
||||
c.String(http.StatusInternalServerError, "Template 'post' not found in current theme: "+themeManager.CurrentTheme()+". Make sure 'post.html' or 'post.tmpl' exists in the theme's templates directory.")
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusOK)
|
||||
c.Header("Content-Type", "text/html; charset=utf-8")
|
||||
// 将整个 content 对象传递给模板。模板内部通过 {{ .Title }} {{ .Text }} 等访问。
|
||||
err = tpl.Execute(c.Writer, content)
|
||||
if err != nil {
|
||||
c.String(http.StatusInternalServerError, "Error rendering template: "+err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user