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 (
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")
	b:= t.New("b")
	t.ExecuteTemplate(os.Stdout,"b", nil)
func main() {

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.

playgroung link:

(Johan Dahl) #2


Parse both into the same template:

or maybe this is a bit more clear

(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.