From 96338dd73e735dd7f254d3380fd49892b62464f6 Mon Sep 17 00:00:00 2001 From: woon Date: Fri, 10 Mar 2023 11:11:43 +0800 Subject: [PATCH] update --- router.go | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/router.go b/router.go index 346279d..5ab3f0e 100644 --- a/router.go +++ b/router.go @@ -1,14 +1,51 @@ package main import ( + "embed" + "fmt" "gin-article/handler" + "path/filepath" + "github.com/gin-contrib/multitemplate" "github.com/gin-gonic/gin" ) +//go:embed tmpl/* +var tmplFs embed.FS + +//go:embed statics/**/* +var staticsFs embed.FS + +func loadTemplates(templatesDir string) multitemplate.Renderer { + r := multitemplate.NewRenderer() + + layouts, err := filepath.Glob(templatesDir + "/layouts/*.html") + if err != nil { + panic(err.Error()) + } + + includes, err := filepath.Glob(templatesDir + "/*.html") + if err != nil { + panic(err.Error()) + } + + // Generate our templates map from our layouts/ and includes/ directories + for _, include := range includes { + layoutCopy := make([]string, len(layouts)) + copy(layoutCopy, layouts) + files := append(layoutCopy, include) + r.AddFromFiles(filepath.Base(include), files...) + } + return r +} + func Router() *gin.Engine { r := gin.Default() + r.HTMLRender = loadTemplates("./tmpl") + fmt.Println(r.HTMLRender) + r.Static("/statics", "statics") + r.GET("/", handler.Index) r.GET("/article/:id", handler.GetArticle)