package main
import (
"github.com/gin-gonic/gin"
"github.com/gin-contrib/multitemplate"
)
func loadTemplates(templatesDir string) multitemplate.Renderer {
r := multitemplate.NewRenderer()
layouts, err := filepath.Glob(templatesDir + "/layouts/*.tmpl")
if err != nil {
panic(err.Error())
}
includes, err := filepath.Glob(templatesDir + "/includes/*.tmpl")
if err != nil {
panic(err.Error())
}
// 为layouts/和includes/目录生成 templates map
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 indexFunc(c *gin.Context){
c.HTML(http.StatusOK, "index.tmpl", nil)
}
func homeFunc(c *gin.Context){
c.HTML(http.StatusOK, "home.tmpl", nil)
}
func main(){
r := gin.Default()
r.HTMLRender = loadTemplates("./templates")
r.GET("/index", indexFunc)
r.GET("/home", homeFunc)
r.Run()
}
github.com/gin-contrib/multitemplate
最新推荐文章于 2026-07-30 23:45:00 发布
该代码示例展示了如何在Go中利用Gin框架和gin-contrib/multitemplate库来加载及渲染HTML模板。它定义了一个`loadTemplates`函数,从指定目录加载布局和包含文件,然后在`main`函数中设置Gin的HTML渲染器并定义了两个路由处理函数`indexFunc`和`homeFunc`,分别用于展示index.tmpl和home.tmpl模板。

277

被折叠的 条评论
为什么被折叠?



