1 demo结构
2 main
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
//创建一个默认的路由引擎
httpServer := gin.Default()
//加载静态文件
httpServer.Static("/static", "./static")
//渲染静态页面
httpServer.LoadHTMLGlob("template/**/*")
//index
httpServer.GET("/index", handlerIndex)
//product
httpServer.GET("/product", handlerProduct)
//启动HTTP服务器
_ = httpServer.Run(":8080")
}
func handlerProduct(c *gin.Context) {
c.HTML(200, "product.html", gin.H{
"title": "product",
"content": "product content",
})
}
func handlerIndex(c *gin.Context) {
c.HTML(200, "index.html", gin.H{
"title": "index",
"content": "index content",
})
}
3 html
base_tmpl.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{.title}}</title>
<link rel="stylesheet" href="static/css/common.css">
</head>
<header style="height: 200px;width: 100%;background: lightgreen;font-size: 20px;">
COMMON HEADER
</header>
<body>
{{block "content" .}}
{{end}}
</body>
<footer style="height: 200px;width: 100%;background: lightcoral;font-size: 20px;">
COMMON FOOTER
</footer>
</html>
index.html:
{{/*继承模板*/}}
{{template "base_tmpl.html" .}}
{{define "content"}}
<h2>{{.content}}</h2>
{{end}}
product.html:
{{/*继承模板*/}}
{{template"base_tmpl.html" .}}
{{define"content"}}
<h2>{{.content}}</h2>
{{end}}