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")
}