Answer the question
In order to leave comments, you need to log in
Nested Golang templates?
Hello. I have a small question about templates in Go. I have created a basic HTML page layout.html and want to use it as a framework for other pages (index.html, terms.html) but dynamically substitute different content. How to do it right?
layout.html:
{{ define "layout" }}
<html>
<body>
{{ block "content" . }}{{ end }}
</body>
</html>
{{ end }}
{{ template "layout" . }}
{{ block "content" . }}
<h1>index</h1>
{{ end }}
{{ template "layout" . }}
{{ block "content" . }}
<h1>terms</h1>
{{ end }}
router := gin.New()
router.LoadHTMLGlob("templates/*")
router.GET("/", func(context *gin.Context) {
context.HTML(http.StatusOK, "index.html", gin.H{})
})
router.GET("/terms", func(context *gin.Context) {
context.HTML(http.StatusOK, "terms.html", gin.H{})
})
Answer the question
In order to leave comments, you need to log in
Block resolution is performed at the moment templates are parsed, not at the moment they are executed. You have everything parsed into one object, so the block that was parsed last is used.
Here is one of the options how to parse into different *Template objects in order to organize layouts.
https://hackernoon.com/golang-template-2-template-...
But it is better to use ready-made solutions for gin, for example https://github.com/foolin/gin-template
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question