diff --git a/actions/detail.go b/actions/detail.go index 5176927..2fc7950 100644 --- a/actions/detail.go +++ b/actions/detail.go @@ -15,7 +15,7 @@ func Detail(c *gin.Context) { var h = gin.H{} var err error defer func() { - c.HTML(http.StatusOK, "detail", h) + c.HTML(http.StatusOK, "posts/detail.gohtml", h) if err != nil { c.Error(err) } diff --git a/actions/index.go b/actions/index.go index 5e94713..f099180 100644 --- a/actions/index.go +++ b/actions/index.go @@ -151,7 +151,7 @@ func Index(c *gin.Context) { ginH := gin.H{} postIds, totalRaw, err := models.SimplePagination[models.WpPosts](h.where, "ID", "", h.page, h.pageSize, h.orderBy, h.join, h.postType, h.status) defer func() { - c.HTML(http.StatusOK, "index", ginH) + c.HTML(http.StatusOK, "posts/index.gohtml", ginH) if err != nil { c.Error(err) } diff --git a/route/route.go b/route/route.go index 2b85082..819f0cc 100644 --- a/route/route.go +++ b/route/route.go @@ -26,8 +26,7 @@ func SetupRouter() *gin.Engine { }, }) reader := templates.NewFsTemplate(r.FuncMap) - reader.AddTemplate("index", "posts/index.gohtml", "layout/*.gohtml") - reader.AddTemplate("detail", "posts/detail.gohtml", "layout/*.gohtml") + reader.AddTemplate() r.HTMLRender = reader r.Use(middleware.SetStaticFileCache) //gzip 因为一般会用nginx做反代时自动使用gzip,所以go这边本身可以不用 diff --git a/templates/templatefs.go b/templates/templatefs.go index 8229bb5..27391f2 100644 --- a/templates/templatefs.go +++ b/templates/templatefs.go @@ -4,6 +4,7 @@ import ( "embed" "github.com/gin-gonic/gin/render" "html/template" + "io/fs" "path/filepath" ) @@ -19,16 +20,24 @@ func NewFsTemplate(funcMap template.FuncMap) *FsTemplate { return &FsTemplate{FuncMap: funcMap, Templates: make(map[string]*template.Template)} } -func (t *FsTemplate) AddTemplate(name, main string, sub ...string) { - tmp := []string{main} - tmp = append(tmp, sub...) - t.Templates[name] = template.Must(template.New(filepath.Base(main)).Funcs(t.FuncMap).ParseFS(TemplateFs, tmp...)) +func (t *FsTemplate) AddTemplate() { + mainTemplates, err := fs.Glob(TemplateFs, "*[^layout]/*.gohtml") + if err != nil { + panic(err) + } + for _, include := range mainTemplates { + name := filepath.Base(include) + in := append([]string{include}, "layout/*.gohtml") + //n := strings.Replace(name, ".gohtml", "", -1) + t.Templates[include] = template.Must(template.New(name).Funcs(t.FuncMap).ParseFS(TemplateFs, in...)) + } } func (t FsTemplate) Instance(name string, data any) render.Render { r := t.Templates[name] return render.HTML{ Template: r, - Data: data, + //Name: name, + Data: data, } }