0

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

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

that worked, thank you very much. i actually missed that field exporting thing, where can i read about it?
@Nickl In the Language specification: Exported Identifiers. The template engine is in a different package (html/template), so the rules apply to it too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.