Gin 框架默認封裝了golang內置的html/template包用于處理html模版,如果你開發的是接口服務,不提供html頁面可以跳過本章內容。
前置技術知識點:
- 模板引擎 - 點擊[Go模板引擎教程](https://www.tizi365.com/archives/85.html),學習完整的模板引擎語法。
## 1.返回html結果的例子
```go
func main() {
// 初始化gin對象
router := gin.Default()
// 首先加載templates目錄下面的所有模版文件,模版文件擴展名隨意
router.LoadHTMLGlob("templates/*")
// 綁定一個url路由 /index
router.GET("/index", func(c *gin.Context) {
// 通過HTML函數返回html代碼
// 第二個參數是模版文件名字
// 第三個參數是map類型,代表模版參數
// gin.H 是map[string]interface{}類型的別名
c.HTML(http.StatusOK, "index.html", gin.H{
"title": "Main website",
})
})
// 啟動http服務,并且綁定在8080端口
router.Run(":8080")
}
```
模版代碼
文件名:templates/index.html
```html
<html>
<h1>
{{ .title }}
</h1>
</html>
```
## 2.處理模版子目錄的情況
一般在項目中,因為有多個模塊的模版文件,我們都會以多個子目錄的方式來組織模版文件,上面的例子只能加載某個目錄下面的模版文件,無法加載子目錄的模版文件。
例子:
```go
func main() {
router := gin.Default()
// 加載templates目錄下面的所有模版文件,包括子目錄
// **/* 代表所有子目錄下的所有文件
router.LoadHTMLGlob("templates/**/*")
router.GET("/posts/index", func(c *gin.Context) {
// 子目錄的模版文件,需要加上目錄名,例如:posts/index.tmpl
c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
"title": "Posts",
})
})
router.GET("/users/index", func(c *gin.Context) {
// 子目錄的模版文件,需要加上目錄名,例如:users/index.tmpl
c.HTML(http.StatusOK, "users/index.tmpl", gin.H{
"title": "Users",
})
})
router.Run(":8080")
}
```
模版文件:templates/posts/index.tmpl
```html
{{ define "posts/index.tmpl" }}
<html><h1>
{{ .title }}
</h1>
<p>Using posts/index.tmpl</p>
</html>
{{ end }}
```
模版文件:templates/users/index.tmpl
```html
{{ define "users/index.tmpl" }}
<html><h1>
{{ .title }}
</h1>
<p>Using users/index.tmpl</p>
</html>
{{ end }}
```
> 更多內容請關注我的博客[SOCKSTACk](https://www.sockstack.cn)