优化模板加载

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 err error
defer func() {
c.HTML(http.StatusOK, "detail", h)
c.HTML(http.StatusOK, "posts/detail.gohtml", h)
if err != nil {
c.Error(err)
}

View File

@ -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)
}

View File

@ -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这边本身可以不用

View File

@ -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,
}
}