S
S
serious9112019-01-02 16:48:30
go
serious911, 2019-01-02 16:48:30

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 }}

on other pages, I override the content block like this:
index.html:
{{ template "layout" . }}
{{ block "content" . }}
<h1>index</h1>
{{ end }}

terms.html:
{{ template "layout" . }}
{{ block "content" . }}
<h1>terms</h1>
{{ end }}

further in the router I generate a page
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{})
})

The problem is that this doesn't work - all pages display the same text from the content block. The routes work, the layout is loaded, but the necessary content from the content block on different pages is not substituted in the templates.
Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2019-01-02
@serious911

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 question

Ask a Question

731 491 924 answers to any question