html 模板渲染
-
gin支持加載HTML模板, 然后根據模板參數進行配置並返回相應的數據,本質上就是字符串替換
-
LoadHTMLGlob()方法可以加載模板文件
加載template文件
1. 加載template文件夾
1.1 template根目錄直接存放
main
func main() {
r := gin.Default()
// 加載模板文件
r.LoadHTMLGlob("templates/*")
// 或者
r.LoadHTMLGlob("./templates/*")
// 或者
r.LoadHTMLFiles("templates/user/index.html")
r.Run()
}
1.2 模板文件分包
main.go
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
routers.Include(home.Routers, auth.Routers)
r := routers.Init()
// 加載模板文件
r.LoadHTMLGlob("templates/**/*")
// 或者
r.LoadHTMLGlob("templates/*/*")
// 或者
r.LoadHTMLGlob("./templates/**/*")
// 或者
r.LoadHTMLGlob("./templates/*/*")
if err := r.Run("0.0.0.0:8888"); err != nil{
fmt.Println("服務端啟動錯誤:",err)
}
}
auth.go
package auth
import (
"encoding/json"
"ginproject/data"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/testdata/protoexample"
"net/http"
)
func loginHandler(ctx *gin.Context) {
if ctx.Request.Method == "GET" {
// 這里依然用ceshi.html即可,因為已經加載到內存中了
ctx.HTML(200, "ceshi.html", gin.H{"title": "測試登錄頁面", "phone": "13784639998"})
} else {
}
}
1.3 加載不同目錄下名稱相同的模板
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")
}
2. 自定義模板渲染器
你可以使用自定義的 html 模板渲染
import "html/template"
func main() {
router := gin.Default()
html := template.Must(template.ParseFiles("file1", "file2"))
router.SetHTMLTemplate(html)
router.Run(":8080")
}
3. 自定義分隔符
r := gin.Default()
// html中取值的符號變為:{[{ .title }]}
r.Delims("{[{", "}]}")
r.LoadHTMLGlob("/path/to/templates")
4. 自定義模板函數
main.go
package main
import (
"fmt"
"ginproject/app/auth"
"ginproject/app/blog"
"ginproject/app/shop"
"ginproject/routers"
"github.com/gin-gonic/gin"
"html/template"
"time"
)
// 時間格式化顯示函數
func formatAsDate(t time.Time) string {
year, month, day := t.Date()
return fmt.Sprintf("%d/%02d/%02d", year, month, day)
}
// 時間格式化顯示函數
func formatAsDate2(t time.Time) string {
year, month, day := t.Date()
return fmt.Sprintf("%d/%02d/%02d", year, month, day)
}
func main() {
routers.Include(shop.Routers, blog.Routers,auth.Routers)
r := routers.Init()
// 設置模板方法
r.SetFuncMap(template.FuncMap{
"formatAsDate":formatAsDate,
"formatAsDate2":formatAsDate2, // map結構,可以設置多個
})
// 加載模板文件
r.LoadHTMLGlob("templates/**/*")
// 靜態文件配置
r.Static("/static", "./static")
if err := r.Run("0.0.0.0:8009"); r != nil {
panic(err.Error())
}
}
raw.tmpl
Date: {[{.now | formatAsDate}]} {# 使用formatAsDate方法進行過濾 #}
執行結果
Date: 2017/07/01
2. 靜態目錄配置
package main
import (
"ginproject/app/auth"
"ginproject/app/blog"
"ginproject/app/shop"
"ginproject/routers"
)
func main() {
routers.Include(shop.Routers, blog.Routers,auth.Routers)
r := routers.Init()
// 加載模板文件
r.LoadHTMLGlob("./templates/*")
// 靜態文件配置
r.Static("/static", "./static")
if err := r.Run("0.0.0.0:8009"); r != nil {
panic(err.Error())
}
}
3. 響應HTML 文件到前端
package auth
import (
"encoding/json"
"ginproject/data"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/testdata/protoexample"
"net/http"
)
func loginHandler(ctx *gin.Context) {
if ctx.Request.Method == "GET" {
ctx.HTML(200, "ceshi.html", gin.H{"title": "測試登錄頁面", "phone": "13784639998"})
} else {
}
}
4. 模板繼承
user/index.html文件代碼:
{{ define "user/index.html" }} {# 這里對外暴露的是user/index.html,所以后端返回的時候也必須得是 user/index.html 如果這里define "index.html" 后端調用也得是index.html,注意加載template文件時在控制台輸出的文件名#}
{{template "public/header" .}}
fgkjdskjdsh{{.address}}
{{template "public/footer" .}}
{{ end }}
public/header.html文件代碼:
{{define "public/header"}}
<!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>
</head>
<body>
<h1>標題</h1>
{{end}}
public/footer.html文件代碼:
{{define "public/footer"}}
<h1>腳部</h1>
</body>
</html>
{{ end }}
auth.go
package auth
import (
"encoding/json"
"ginproject/data"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/testdata/protoexample"
"net/http"
)
func loginHandler(ctx *gin.Context) {
if ctx.Request.Method == "GET" {
// user/index.html 對外暴露的是user/index.html,所以后端返回的時候也必須得是 user/index.html
ctx.HTML(200, "user/index.html", gin.H{"title": "測試登錄頁面", "address": "13784639998"})
} else {}
}
5. 多模板渲染
https://github.com/gin-contrib/multitemplate
6. 重定向
路由
e.GET("/redirect",RedirectHandler)
handler.go
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func RedirectHandler(ctx *gin.Context) {
ctx.Redirect(http.StatusMovedPermanently,"http://www.baidu.com")
}