6_gin日拱一足---- HTML模板渲染
gin日拱一足---- HTML模板渲染
<!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>
fgkjdskjdsh{{.ce}}
</body>
</html>
渲染上述的html文件
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
//HTML模板文件的解析 我们要解析./template下的login.html
r := gin.Default()
//加载template模板文件
r.LoadHTMLGlob("template/*") //"template/**/*":template所有目录下的所有表
r.GET("/",func(c *gin.Context){
c.HTML(http.StatusOK,"login.html",gin.H{
"title": "这是一个title",
"ce": "chenjunde",
})
})
r.Run()
}
可以去做一些模板的嵌套操作:
{{ define "user/index.html" }} //定义模板的名字 防止解析模板时发生冲突
{{template "public/header" .}} //嵌套模板"pubilic/header" --> 注意后边的.
fgkjdskjdsh{{.address}}
{{template "public/footer" .}} //嵌套模板"public/footer" ---> 注意后边的.
{{ end }}
{{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>
{{end}}
{{define "public/footer"}}
</body>
</html>
{{ end }}
静态文件的加载(css js png等等)
r.Static("/assets", "./assets") //声明要加载/assets下的静态文件时 去当前main执行程序的./assets位置去查找