使用 LoadHTMLGlob() 或者 LoadHTMLFiles()
```go
func main() {
router := gin.Default()
router.LoadHTMLGlob("templates/*")
//router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")
router.GET("/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.tmpl", gin.H{
"title": "Main website",
})
})
router.Run(":8080")
}
```
templates/index.tmpl
```html
<html>
<h1>
{{ .title }}
</h1>
</html>
```
使用不同目錄下名稱相同的模板
```go
func main() {
router := gin.Default()
router.LoadHTMLGlob("templates/**/*")
router.GET("/posts/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
"title": "Posts",
})
})
router.GET("/users/index", func(c *gin.Context) {
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 }}
```
#### 自定義模板渲染器
你可以使用自定義的 html 模板渲染
```go
import "html/template"
func main() {
router := gin.Default()
html := template.Must(template.ParseFiles("file1", "file2"))
router.SetHTMLTemplate(html)
router.Run(":8080")
}
```
#### 自定義分隔符
你可以使用自定義分隔
```go
r := gin.Default()
r.Delims("{[{", "}]}")
r.LoadHTMLGlob("/path/to/templates")
```
#### 自定義模板功能
查看詳細[示例代碼](https://github.com/gin-gonic/examples/tree/master/template)。
main.go
```go
import (
"fmt"
"html/template"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
func formatAsDate(t time.Time) string {
year, month, day := t.Date()
return fmt.Sprintf("%d/%02d/%02d", year, month, day)
}
func main() {
router := gin.Default()
router.Delims("{[{", "}]}")
router.SetFuncMap(template.FuncMap{
"formatAsDate": formatAsDate,
})
router.LoadHTMLFiles("./testdata/template/raw.tmpl")
router.GET("/raw", func(c *gin.Context) {
c.HTML(http.StatusOK, "raw.tmpl", map[string]interface{}{
"now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC),
})
})
router.Run(":8080")
}
```
raw.tmpl
```sh
Date: {[{.now | formatAsDate}]}
```
結果:
```sh
Date: 2017/07/01
```
- 介紹
- 快速入門
- 基準測試
- 特性
- Jsoniter
- 示例
- AsciiJSON
- HTML 渲染
- HTTP2 server 推送
- JSONP
- Multipart/Urlencoded 綁定
- Multipart/Urlencoded 表單
- PureJSON
- Query 和 post form
- SecureJSON
- XML/JSON/YAML/ProtoBuf 渲染
- 上傳文件
- 單文件
- 多文件
- 不使用默認的中間件
- 從 reader 讀取數據
- 優雅地重啟或停止
- 使用 BasicAuth 中間件
- 使用 HTTP 方法
- 使用中間件
- 只綁定 url 查詢字符串
- 在中間件中使用 Goroutine
- 多模板
- 如何記錄日志
- 定義路由日志的格式
- 將 request body 綁定到不同的結構體中
- 支持 Let's Encrypt
- 映射查詢字符串或表單參數
- 查詢字符串參數
- 模型綁定和驗證
- 綁定 HTML 復選框
- 綁定 Uri
- 綁定查詢字符串或表單數據
- 綁定表單數據至自定義結構體
- 自定義 HTTP 配置
- 自定義中間件
- 自定義驗證器
- 設置和獲取 Cookie
- 路由參數
- 路由組
- 運行多個服務
- 重定向
- 靜態文件服務
- 靜態資源嵌入
- 測試
- 用戶
- FAQ