Gin勉強の備忘録
multitemplateのインストール
go get github.com/gin-contrib/multitemplate
構成
Project名
├── main.go
└── views
├── templates
│ ├── template.html
└── index
├── index1.html
└── index2.html
render.AddFromFiles(name string, ...filename string)
第一引数"name"をctx.HTML(http.statusOK, "*****", gin.H{})の第二引数に入れる
main.go
package controller
import (
"net/http"
"github.com/gin-contrib/multitemplate"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.LoadHTMLFiles("views/**/*.html")
router.HTMLRender = createMyRender()
router.GET("/1", func(ctx *gin.Context) {
ctx.HTML(http.StatusOK, "index1", gin.H{
"title": "index1",
})
})
router.GET("/2", func(ctx *gin.Context) {
ctx.HTML(http.StatusOK, "index2", gin.H{
"title": "index2",
})
})
router.Run()
}
func createMyRender() multitemplate.Renderer {
render := multitemplate.NewRenderer()
//render.AddFromFiles(name string, ...filename string)
render.AddFromFiles("index1", "templates/template.html", "index/index1.html")
render.AddFromFiles("index2", "tmeplates/template.html", "index/index2.html")
return render
}
template.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>{{.title}}</title>
</head>
<body>
{{template "index" . }}
</body>
</html>
index1.html
{{define "index"}}
<h1>this is index1</h1>
{{end}}
index2.html
{{define "index"}}
<h1>this is index2</h1>
{{end}}