How do you pass structs to subtemplates in go?

Issue

I am trying to understand how to use the same template in Go several time passing different structs.

This is what I have tried:

import (
    "fmt"
    "html/template"
    "os"
)

type person struct {
    id    int
    name  string
    phone string
}

type page struct {
    p1 person
    p2 person
}

func main() {
    p1 := person{1, "Peter", "1001"}
    p2 := person{2, "Mary", "1002"}
    p := page{p1, p2}

    fmt.Println(p)

    t := template.Must(template.New("foo").Parse(`
    {{define "s1"}}
    <span id="{{.id}}">{{.name}} {{.phone}}</span>
    {{end}}
    {{template "s1" {{.p1}}}}{{template "s1" {{.p2}}}}
    `))

    t.Execute(os.Stdout, p)
}

But it does not work as expected:

panic: template: foo:5: unexpected "{" in template clause

The expected output is:

<span id="1">Peter 1001</span><span id="2">Mary 1002</span>

Solution

When you call the template function, you give 2 arguments (separated by a space):

  • A defined template name ("s1")
  • You object: .p1 in your case

So here is a working template in your case:

    t := template.Must(template.New("foo").Parse(`
    {{ define "s1" }}
        <span id="{{ .id }}">{{.name}} {{ .phone }}</span>
    {{ end }}

    {{ template "s1" .p1 }}
    {{ template "s1" .p2 }}
    `))
}

Answered By – Vincent Composieux

Answer Checked By – Timothy Miller (GoLangFix Admin)

Leave a Reply

Your email address will not be published.