Skip to content

Instantly share code, notes, and snippets.

@anhtran
Last active July 9, 2023 16:09
Show Gist options
  • Save anhtran/9150054167b20ec62ccc to your computer and use it in GitHub Desktop.
Save anhtran/9150054167b20ec62ccc to your computer and use it in GitHub Desktop.
Multiple template files in Go with gin framework
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{if .title}}{{.title}}{{else}}{{block "title" .}}My Website{{end}}{{end}}</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
{{block "media_head" .}}{{end}}
</head>
<body>
<div class="container">
{{template "content" .}}
</div>
<script src="/static/bower_components/jquery/dist/jquery.min.js"></script>
{{block "media_foot" .}}{{end}}
</body>
</html>
{{define "title"}}Homepage{{end}}
{{define "content"}}
<div class="home">
<p>Hello</p>
</div>
{{end}}
{{define "media_foot"}}
<script src="/static/js/home.js"></script>
{{end}}
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
router.HTMLRender = makeTemplates()
// views
router.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "home", gin.H{
"title": "Hello Golang!"
})
});
router.Run(":6969")
}
package main
import (
"github.com/gin-gonic/contrib/renders/multitemplate"
)
func makeTemplates() multitemplate.Render {
templates := multitemplate.New()
templates.AddFromFiles("home",
"base.html",
"home.html",
)
return templates
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment