hmtl 渲染
最后更新于:2022-04-02 02:47:51
[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
```
';
{{ .title }}
``` ## 使用不同目录下名称相同的模板 ``` 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" }}{{ .title }}
Using posts/index.tmpl
{{ 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 }} ```