英文:
golang html template doesn't display anything
问题
我有这段用于html/template的代码,但它无法运行。我想要显示数组中的每个元素,但它没有返回任何内容。请忽略ioutil文件读取部分。
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)
}
和welcome.html:
{{range .test}}
item
{{end}}
英文:
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
得分: 3
Page.test
字段没有被导出,它以小写字母开头。模板引擎(就像其他所有东西一样)只能访问导出的字段。
将其更改为:
type Page struct {
Test [3]Person
Test2 string
}
并且在引用它的所有其他地方也进行更改,例如 p := Page{Test: a}
。还要在模板中进行更改:
{{range .Test}}
item
{{end}}
**还有:永远不要忽略检查错误!**你至少可以使用 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)
}
在Go Playground上尝试一下。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论