一、模板的使用
1、加載模板路徑
當使用gin.Default方法創建一個router后需要加載模板路徑,加載的方法可以使用:
-
LoadHTMLGlob 只有一個參數,通配符,如:router.LoadHTMLGlob("templates/*"),查找當前項目路徑下template文件夾下所有的html文件
- LoadHTMLFiles 不定長參數,可以傳多個字符串,如:router.LoadHTMLFiles("template/index.html","template/user.html"),指定所有要使用的html文件路徑
推薦使用LoadHTMLGlob ,如果存在多級目錄可以這樣指定:
兩級:engine.LoadHTMLGlob("templates/**/*") 三級:engine.LoadHTMLGlob("templates/**/**/*") ...
2、掛載路由
router.GET("/index", Hello)
3、編寫視圖函數
func Hello(ctx *gin.Context) { ctx.HTML(http.StatusOK, "home/index.html","hello home!") }
在試圖函數中指定模板路徑以及渲染到前端的數據。
4、模板文件編寫
在項目的template目錄下新建home目錄然后新建index.html文件:
{{ define "home/index.html"}} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/css/index.css"> </head> <body> <div class="content">{{ . }}</div> </body> </html> {{ end }}
對於二級以及多級目錄需要在文件開頭通過define指定文件的路徑,否則程序識別不到。
5、啟動程序
func main() { router := gin.Default() // 加載模板路徑 router.LoadHTMLGlob("template/**/*") router.GET("/index", Hello) router.Run(":8080") }
通過router.Run方法啟動,注意不要在IDE中啟動,通過cmd窗口的方式,否則模板找不到。
二、靜態文件的使用
當使用html時,難免使用到css、js、images等,此時需要一種方式進行引入。
1、加載靜態文件
func main() { router := gin.Default() // 加載模板路徑 router.LoadHTMLGlob("template/**/*") // 加載靜態文件,注意第一個路徑參數映射第二個目錄參數,所以第一個參數可以隨意,但是在html中引入時需要與其保持一致 router.Static("/static", "static") router.GET("/index", Hello) router.Run(":8080") }
2、模板中引入
{{ define "home/index.html"}} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/css/index.css"> </head> <body> <div class="content">{{ . }}</div> </body> </html> {{ end }}
三、項目說明
1、項目結構
demo01
│ main.go
│ README.md
│
├─static
│ ├─css
│ │ index.css
│ │
│ ├─images
│ └─js
└─template
├─goods
│ goods.html
│
├─home
│ index.html
│
└─order
order.html
2、主要文件說明
- main.go
package main import ( "github.com/gin-gonic/gin" "net/http" ) func Hello(ctx *gin.Context) { ctx.HTML(http.StatusOK, "home/index.html","hello home!") } func main() { router := gin.Default() // 加載模板路徑 二級目錄 router.LoadHTMLGlob("template/**/*") // 加載靜態文件 router.Static("/static", "static") router.GET("/index", Hello) router.Run(":8080") }