Nickl Nickl - 3 months ago 14
HTML Question

golang html template doesn't display anything

I have this code for html/template, and it won't run. I want to display each element in the array and it will return nothing. Please ignore the ioutil file reading.

type Person struct {
Name string
Age int
}

type Page struct {
test [3]Person
test2 string
}

func main() {
var a [3]Person
a[0] = Person{Name: "test", Age: 20}
a[1] = Person{Name: "test", Age: 20}
a[2] = Person{Name: "test", Age: 20}

p:= Page{test: a}

c, _ := ioutil.ReadFile("welcome.html")
s := string(c)

t := template.New("")
t, _ = t.Parse(s)
t.Execute(os.Stdout, p)
}


and welcome.html:

{{range .test}}
item
{{end}}

Answer

The Page.test field is not exported, it starts with a lowercase letter. The template engine (just like everything else) can only access exported fields.

Change it to:

type Page struct {
    Test [3]Person
    Test2 string
}

And all the other places where you refer to it, e.g. p:= Page{Test: a}. And also in the template:

{{range .Test}}
    item
{{end}}

And also: never omit checking errors! The least you can do is panic:

c, err := ioutil.ReadFile("welcome.html") 
if err != nil {
    panic(err)
}
s := string(c)

t := template.New("")
t, err = t.Parse(s)
if err != nil {
    panic(err)
}
err = t.Execute(os.Stdout, p)
if err != nil {
    panic(err)
}

Try it on the Go Playground.