ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 简单实例 ``` 使用 LoadHTMLGlob() 或者 LoadHTMLFiles() func main() { router := gin.Default() router.LoadHTMLGlob("templates/*") //router.LoadHTMLFiles("templates/template1.html", "templates/template2.html") router.GET("/index", func(c *gin.Context) { c.HTML(http.StatusOK, "index.tmpl", gin.H{ "title": "Main website", }) }) router.Run(":8080") } ``` templates/index.tmpl ``` <html> <h1> {{ .title }} </h1> </html> ``` ## 使用不同目录下名称相同的模板 ``` func main() { router := gin.Default() router.LoadHTMLGlob("templates/**/*") router.GET("/posts/index", func(c *gin.Context) { c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{ "title": "Posts", }) }) router.GET("/users/index", func(c *gin.Context) { c.HTML(http.StatusOK, "users/index.tmpl", gin.H{ "title": "Users", }) }) router.Run(":8080") } ``` templates/posts/index.tmpl ``` {{ define "posts/index.tmpl" }} <html><h1> {{ .title }} </h1> <p>Using posts/index.tmpl</p> </html> {{ end }} ``` ## 自定义函数 ``` func echoHello(t string) string { return t+" word" } func main() { router := gin.Default() router.SetFuncMap(template.FuncMap{ "echoHello": echoHello, }) router.LoadHTMLGlob("./templates/*") router.GET("/index", func(c *gin.Context) { c.HTML(http.StatusOK, "index.html", gin.H{ "hello": "word", }) }) router.Run(":8080") } ``` templates/index.html ``` {{ .hello | echoHello }} ```