Trying to understand Text/Template Blocks


(Cristian Maluenda) #1

Hi everybody,
yes, I am another new go developer and I am trying to understand why my template doesn’t work as I expected. I have this:

Template 1:
{{ define "myblock"}} some text {{ end }}

Template 2:
here is {{ block "myblock" . }} another text {{ end }}

Go app :

package main

import (
	"text/template"
	"os"
)
var template1 = `here is {{ block "myblock" . }}another text{{ end }}`
var template2 = `{{ define "myblock"}}some text{{ end }}`

func test() {
	t:= template.New("base")

	a:= t.New("a")
	a.Parse(template2)
	b:= t.New("b")
	b.Parse(template1)
	t.ExecuteTemplate(os.Stdout,"b", nil)
}
func main() {
	test()       
}

The output file has this text: here is another text but I will expect here is some text.
But, the weird thing is if Template 2 has an empty block:
here is {{ block "myblock" . }} {{ end }}
The output is the expected: here is some text.

I don’t know if this behavior is the expected, or I have some issues because I use Go routine or not.
Thanks!

playgroung link: https://play.golang.org/p/32QkEhhtX6T


(Johan Dahl) #2

Hi

Parse both into the same template:

https://play.golang.org/p/MX88bm8AuUW

or maybe this is a bit more clear

https://play.golang.org/p/-K4agi6bJ1x


(Cristian Maluenda) #3

Thanks for your help.
I realized that I need to parse first the template with the block, and then the template with the define. Also, I couldn’t use the same template to parse all because I need to write in disc each template in a new file.