模板渲染

模板是golang语言的一个标准库,使用场景很多,gin框架同样支持模板

1. 基本使用

定义一个存放模板文件的templates文件夹

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>gin_templates</title>
</head>
<body>
{{.title}}
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11

后端代码:

package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func main() {
	r := gin.Default()
	// 模板解析
	r.LoadHTMLFiles("templates/index.tmpl")

	r.GET("/index", func(c *gin.Context) {
		// HTML请求
		// 模板的渲染
		c.HTML(http.StatusOK, "index.tmpl", gin.H{
			"title": "hello 模板",
		})
	})

	r.Run(":9090") // 启动server
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

2. 多个模板渲染

如果有多个模板,可以统一进行渲染

// 模板解析,解析templates目录下的所有模板文件
	r.LoadHTMLGlob("templates/**")
1
2

如果目录为templates/post/index.tmpltemplates/user/index.tmpl这种,可以

	// **/* 代表所有子目录下的所有文件
	router.LoadHTMLGlob("templates/**/*")
1
2

3. 自定义模板函数

   // gin框架给模板添加自定义函数
	r.SetFuncMap(template.FuncMap{
		"safe": func(str string) template.HTML {
			return template.HTML(str)
		},
	})

	// 模板解析,解析templates目录下的所有模板文件
	r.LoadHTMLGlob("templates/**")

	r.GET("/index", func(c *gin.Context) {
		// HTML请求
		// 模板的渲染
		c.HTML(http.StatusOK, "index.tmpl", gin.H{
			"title": "<a href='http://baidu.com'>跳转到其他地方</a>",
		})
	})

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>gin_templates</title>
</head>
<body>
{{.title | safe}}
</body>
</html>

1
2
3
4
5
6
7
8
9
10
11
12

4. 静态文件处理

如果在模板中引入静态文件,比如样式文件

index.css

body{
    background-color: aqua;
}
1
2
3
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>gin_templates</title>
    <link rel="stylesheet" href="/css/index.css">
</head>
<body>
{{.title}}
</body>
</html>

1
2
3
4
5
6
7
8
9
10
11
12
13
// 加载静态文件
r.Static("/css", "./static/css")
1
2