package main import ( "github.com/gin-gonic/gin" "net/http" ) func login(ctx *gin.Context) { ctx.JSON(http.StatusOK, map[string]interface{}{ "username": "李四", "password": 123465, }) } func main() { // HTML渲染, router := gin.Default() //router.LoadHTMLFiles("templates/index.html", "templates/login.html") //router.LoadHTMLGlob("templates/*") // 使用不同目录下名称相同的模板 router.LoadHTMLGlob("templates/**/*") router.GET("/users/index", func(context *gin.Context) { context.HTML(http.StatusOK, "users/index.html", gin.H{ "title": "Users", }) }) router.GET("/center/index", func(context *gin.Context) { context.HTML(http.StatusOK, "center/index.html", gin.H{ "title": "Center", }) }) router.GET("/login", login) router.Run() }
目录结构
html代码
<!DOCTYPE html> {{ define "center/index.html" }} <html lang="en"> <head> <meta charset="UTF-8"> <title>首页</title> </head> <body> <h1>{{ .title }}</h1> </body> </html> {{ end }}
2. 自定义HTML模板渲染器
package main import ( "github.com/gin-gonic/gin" "html/template" "net/http" ) func main() { router := gin.Default() // 自定义html模板渲染器,要指定所有的html路径,不推荐 html := template.Must(template.ParseFiles( "templates/login.html", "templates/users/index.html", "templates/center/index.html", )) router.SetHTMLTemplate(html) router.GET("/users/index", func(context *gin.Context) { context.HTML(http.StatusOK, "users/index.html", gin.H{ "title": "users/index.html", }) }) router.Run() }
3. 自定义分隔符、模板功
package main import ( "fmt" "github.com/gin-gonic/gin" "html/template" "net/http" "time" ) 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.LoadHTMLGlob("templates/**/*") router.GET("/users/index", func(context *gin.Context) { context.HTML(http.StatusOK, "users/index.html", map[string]interface{}{ "now": time.Date(2021, 10, 15, 0, 0, 0, 0, time.Local), }) }) router.Run() }
hmtl代码
<!DOCTYPE html> {[{ define "users/index.html" }]} <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2> {[{ .now | formatAsDate }]} </h2> </body> </html> {[{ end }]}