Last active
July 9, 2023 16:09
-
-
Save anhtran/9150054167b20ec62ccc to your computer and use it in GitHub Desktop.
Multiple template files in Go with gin framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{{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}} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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