优化模板加载

This commit is contained in:
xing 2022-09-19 12:36:51 +08:00
parent 979740bebc
commit e178a7bc91
4 changed files with 17 additions and 9 deletions

View File

@ -15,7 +15,7 @@ func Detail(c *gin.Context) {
var h = gin.H{} var h = gin.H{}
var err error var err error
defer func() { defer func() {
c.HTML(http.StatusOK, "detail", h) c.HTML(http.StatusOK, "posts/detail.gohtml", h)
if err != nil { if err != nil {
c.Error(err) c.Error(err)
} }

View File

@ -151,7 +151,7 @@ func Index(c *gin.Context) {
ginH := gin.H{} 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) postIds, totalRaw, err := models.SimplePagination[models.WpPosts](h.where, "ID", "", h.page, h.pageSize, h.orderBy, h.join, h.postType, h.status)
defer func() { defer func() {
c.HTML(http.StatusOK, "index", ginH) c.HTML(http.StatusOK, "posts/index.gohtml", ginH)
if err != nil { if err != nil {
c.Error(err) c.Error(err)
} }

View File

@ -26,8 +26,7 @@ func SetupRouter() *gin.Engine {
}, },
}) })
reader := templates.NewFsTemplate(r.FuncMap) reader := templates.NewFsTemplate(r.FuncMap)
reader.AddTemplate("index", "posts/index.gohtml", "layout/*.gohtml") reader.AddTemplate()
reader.AddTemplate("detail", "posts/detail.gohtml", "layout/*.gohtml")
r.HTMLRender = reader r.HTMLRender = reader
r.Use(middleware.SetStaticFileCache) r.Use(middleware.SetStaticFileCache)
//gzip 因为一般会用nginx做反代时自动使用gzip,所以go这边本身可以不用 //gzip 因为一般会用nginx做反代时自动使用gzip,所以go这边本身可以不用

View File

@ -4,6 +4,7 @@ import (
"embed" "embed"
"github.com/gin-gonic/gin/render" "github.com/gin-gonic/gin/render"
"html/template" "html/template"
"io/fs"
"path/filepath" "path/filepath"
) )
@ -19,16 +20,24 @@ func NewFsTemplate(funcMap template.FuncMap) *FsTemplate {
return &FsTemplate{FuncMap: funcMap, Templates: make(map[string]*template.Template)} return &FsTemplate{FuncMap: funcMap, Templates: make(map[string]*template.Template)}
} }
func (t *FsTemplate) AddTemplate(name, main string, sub ...string) { func (t *FsTemplate) AddTemplate() {
tmp := []string{main} mainTemplates, err := fs.Glob(TemplateFs, "*[^layout]/*.gohtml")
tmp = append(tmp, sub...) if err != nil {
t.Templates[name] = template.Must(template.New(filepath.Base(main)).Funcs(t.FuncMap).ParseFS(TemplateFs, tmp...)) 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 { func (t FsTemplate) Instance(name string, data any) render.Render {
r := t.Templates[name] r := t.Templates[name]
return render.HTML{ return render.HTML{
Template: r, Template: r,
Data: data, //Name: name,
Data: data,
} }
} }