gin渲染
我们首先定义一个存放模板文件的templates文件夹,然后在其内部按照业务分别定义一个posts文件夹和一个users文件夹。 posts/index.html文件的内容如下:
{{define "posts/index.html"}}
<!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}}
users/index.html文件的内容如下:
{{define "users/index.html"}}
<!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}}
Gin框架中使用LoadHTMLGlob()一般是加载所有文件使用或者LoadHTMLFiles()一般是加载单个文件,进行HTML模板渲染。
func main() {
r := gin.Default()
//使用正则表达式加载 /**/表示加载这下面两个文件 /*加载下面所有的文件
r.LoadHTMLGlob("templates/**/*")
//r.LoadHTMLFiles("templates/posts/index.html", "templates/users/index.html")
r.GET("/posts/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "posts/index.html", gin.H{
"title": "posts/index",
})
})
r.GET("users/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "users/index.html", gin.H{
"title": "users/index",
})
})
r.Run(":8080")
}
自定义模板函数
定义一个不转义相应内容的return模板函数如下
func main() {
router := gin.Default()
router.SetFuncMap(template.FuncMap{
"return": 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中使用定义好的return模板函数:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>调用模板自定义函数</title>
</head>
<body>
<div>{{ . | return }}</div>
</body>
</html>
静态文件处理
当我们渲染的文件引用了静态文件时,我们只需调用gin.Static方法,示例如下:
func main() {
r := gin.Default()
r.Static("/static", "./static")
r.LoadHTMLGlob("templates/**/*")
// ...
r.Run(":8080")
}