1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Go/Gin HTMLテンプレートの使い方

Last updated at Posted at 2022-12-08

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}}
1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?