HTML渲染
最后更新于:2022-04-02 07:26:54
使用`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 }} ``` templates/users/index.tmpl ``` {{ define "users/index.tmpl" }}{{ .title }}
Using users/index.tmpl
{{ end }} ``` **自定义模板渲染器** ``` import "html/template" func main() { router := gin.Default() html := template.Must(template.ParseFiles("file1", "file2")) router.SetHTMLTemplate(html) router.Run(":8080") } ``` **自定义渲染分隔符** ``` r := gin.Default() r.Delims("{[{", "}]}") r.LoadHTMLGlob("/path/to/templates") ``` **自定义模板函数** [详细信息](https://github.com/gin-gonic/gin/blob/master/examples/template) main.go ``` import ( "fmt" "html/template" "net/http" "time" "github.com/gin-gonic/gin" ) func formatAsDate(t time.Time) string { year, month, day := t.Date() return fmt.Sprintf("%d%02d/%02d", year, month, day) } func main() { router := gin.Default() router.Delims("{[{", "}]}") router.SetFuncMap(template.FuncMap{ "formatAsDate": formatAsDate, }) router.LoadHTMLFiles("./testdata/template/raw.tmpl") router.GET("/raw", func(c *gin.Context) { c.HTML(http.StatusOK, "raw.tmpl", map[string]interface{}{ "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC), }) }) router.Run(":8080") } ``` raw.tmpl 然后就可以在html中直接使用formatAsDate函数了 ``` Date: {[{.now | formatAsDate}]} ``` Result: ``` Date: 2017/07/01 ```