Gin框架中使用LoadHTMLGlob()或者LoadHTMLFiles()方法进行HTML模板渲染。
templates
├── index.tmpl
├── main.go
├── go.mod
│ └── go.sum
├── 外部库
└── 临时文件和控制台
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.LoadHTMLFiles("template/index.tmpl") //模版解析
r.GET("/index", func(c *gin.Context) {
// HTTP请求
c.HTML(http.StatusOK, "index.tmpl", gin.H{ // 模版渲染
"title": "jiejaitt.blog.csdn.net",
})
})
r.Run(":8080")
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>posts/index</title>
</head>
<body>
{{.title}}
</body>
</html>
渲染多个模版文件
main.go
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
//r.LoadHTMLFiles("template/index.tmpl", "tmplates/users/index.tmpl") //模版解析
r.LoadHTMLGlob("template/**/*")
r.GET("posts/index", func(c *gin.Context) {
// HTTP请求
c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{ // 模版渲染
"title": "jiejaitt.blog.csdn.net",
})
})
r.GET("users/index", func(c *gin.Context) {
// HTTP请求
c.HTML(http.StatusOK, "users/index.tmpl", gin.H{ // 模版渲染
"title": "jiejaitt.notion.site",
})
})
r.Run(":8080")
}
user/index.tmpl
{{define "users/index.tmpl"}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>users/index</title>
</head>
<body>
{{.title}}
</body>
</html>
{{end}}
posts/index.tmpl
{{define "posts/index.tmpl"}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>posts/index</title>
</head>
<body>
{{.title}}
</body>
</html>
{{end}}
自定义模板函数
定义一个不转义相应内容的safe
模板函数如下:
func main() {
router := gin.Default()
router.SetFuncMap(template.FuncMap{
"safe": func(str string) template.HTML{
return template.HTML(str)
},
})
router.LoadHTMLFiles("./index.tmpl")
router.GET("/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.tmpl", "<a href='https://liwenzhou.com'>李文周的博客</a>")
})
router.Run(":8080")
}
在index.tmpl
中使用定义好的safe
模板函数:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>修改模板引擎的标识符</title>
</head>
<body>
<div>{{ . | safe }}</div>
</body>
</html>