1. 簡單應用
-
Gin 支持 HTML 模板,然后將參數渲染到模板頁面並返回,本質上是對頁面內容進行字符串替換
-
可以使用
LoadHTMLGlob(pattern string)
方法加載模板文件g := gin.Default() g.LoadHTMLGlob("template/**/*")
1.1 單目錄結構
- 目錄結構如下
|- template
|- index.html
|- main.go
main.go
代碼:
func main() {
g := gin.Default()
// 加載 template 目錄下的模板文件
g.LoadHTMLGlob("template/*")
g.GET("/index", func(ctx *gin.Context) {
ctx.HTML(http.StatusOK, "index.html", gin.H{
"title": "HTML 模板渲染樣例",
"body": "這里是內容",
})
})
g.Run()
}
template/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>{{ .title }}</title>
<!-- 會被替換成以下注釋中的內容 -->
<!-- <title>HTML 模板渲染樣例</title> -->
</head>
<body>
{{ .body }}
<!-- 會被替換成以下注釋中的內容 -->
<!-- 這里是內容 -->
</body>
</html>
1.2 多級目錄結構
- 目錄結構如下
|- template
|- user
|- index.html
|- main.go
main.go
代碼:
func main() {
g := gin.Default()
// 加載 template 目錄下的模板文件
g.LoadHTMLGlob("template/**/*")
g.GET("/index", func(ctx *gin.Context) {
ctx.HTML(http.StatusOK, "user/index.html", gin.H{
"title": "HTML 模板渲染樣例",
"body": "這里是內容",
})
})
g.Run()
}
template/user/index.html
代碼:
{{ define "user/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>{{ .title }}</title>
<!-- 會被替換成以下注釋中的內容 -->
<!-- <title>HTML 模板渲染樣例</title> -->
</head>
<body>
{{ .body }}
<!-- 會被替換成以下注釋中的內容 -->
<!-- 這里是內容 -->
</body>
</html>
{{ end }}
2. 模板復用
- 目錄結構如下:
|- static
|- template
|- public
|- footer.html
|- header.html
|- user
|- index.html
|- main.go
main.go
代碼:
func main() {
g := gin.Default()
// 加載 template 目錄下的模板文件
g.LoadHTMLGlob("template/**/*")
g.GET("/index", func(ctx *gin.Context) {
ctx.HTML(http.StatusOK, "user/index.html", gin.H{
"title": "HTML 模板渲染樣例",
"body": "這里是內容",
})
})
g.Run()
}
user/index.html
代碼:
{{ define "user/index.html" }}
<!DOCTYPE html>
<html lang="en">
{{ template "public/header" . }}
{{ template "public/footer" . }}
</html>
{{ end }}
public/header.html
代碼:
{{ define "public/header" }}
<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>{{ .title }}</title>
<!-- 會被替換成以下注釋中的內容 -->
<!-- <title>HTML 模板渲染樣例</title> -->
</head>
{{ end }}
public/footer.html
代碼:
{{ define "public/footer" }}
<body>
{{ .body }}
<!-- 會被替換成以下注釋中的內容 -->
<!-- 這里是內容 -->
</body>
{{ end }}
3. 靜態資源文件映射
- 可以使用
Static(uriPath, rootPath string)
方法配置靜態資源文件目錄
g.Static("/static", "./static")