1. HTML模板渲染

  • gin支持加载HTML模板, 然后根据模板参数进行配置并返回相应的数据,本质上就是字符串替换
  • LoadHTMLGlob()方法可以加载模板文件
  1. package main
  2. import (
  3. "net/http"
  4. "github.com/gin-gonic/gin"
  5. )
  6. func main() {
  7. r := gin.Default()
  8. r.LoadHTMLGlob("tem/*")
  9. r.GET("/index", func(c *gin.Context) {
  10. c.HTML(http.StatusOK, "index.html", gin.H{"title": "我是测试", "ce": "123456"})
  11. })
  12. r.Run()
  13. }
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <title>{{.title}}</title>
  8. </head>
  9. <body>
  10. fgkjdskjdsh{{.ce}}
  11. </body>
  12. </html>

目录结构:

HTML模板渲染 - 图1

  • 如果你的目录结构是下面的情况

HTML模板渲染 - 图2

代码如下:

  1. package main
  2. import (
  3. "net/http"
  4. "github.com/gin-gonic/gin"
  5. )
  6. func main() {
  7. r := gin.Default()
  8. r.LoadHTMLGlob("tem/**/*")
  9. r.GET("/index", func(c *gin.Context) {
  10. c.HTML(http.StatusOK, "user/index.html", gin.H{"title": "我是测试", "address": "www.5lmh.com"})
  11. })
  12. r.Run()
  13. }
  1. {{ define "user/index.html" }}
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <head>
  5. <meta charset="UTF-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  8. <title>{{.title}}</title>
  9. </head>
  10. <body>
  11. fgkjdskjdsh{{.address}}
  12. </body>
  13. </html>
  14. {{ end }}
  • 如果你想进行头尾分离就是下面这种写法了:

HTML模板渲染 - 图3

  1. package main
  2. import (
  3. "net/http"
  4. "github.com/gin-gonic/gin"
  5. )
  6. func main() {
  7. r := gin.Default()
  8. r.LoadHTMLGlob("tem/**/*")
  9. r.GET("/index", func(c *gin.Context) {
  10. c.HTML(http.StatusOK, "user/index.html", gin.H{"title": "我是测试", "address": "www.5lmh.com"})
  11. })
  12. r.Run()
  13. }

user/index.html文件代码:

  1. {{ define "user/index.html" }}
  2. {{template "public/header" .}}
  3. fgkjdskjdsh{{.address}}
  4. {{template "public/footer" .}}
  5. {{ end }}

public/header.html文件代码:

  1. {{define "public/header"}}
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <head>
  5. <meta charset="UTF-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  8. <title>{{.title}}</title>
  9. </head>
  10. <body>
  11. {{end}}

public/footer.html文件代码:

  1. {{define "public/footer"}}
  2. </body>
  3. </html>
  4. {{ end }}
  • 如果你需要引入静态文件需要定义一个静态文件目录
  1. r.Static("/assets", "./assets")