gpt4 book ai didi

html - golang html 模板不显示任何内容

转载 作者:IT王子 更新时间:2023-10-29 02:34:08 26 4
gpt4 key购买 nike

我有这段用于 html/模板的代码,但它无法运行。我想显示数组中的每个元素,它不会返回任何内容。请忽略 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}}

最佳答案

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 上试试.

关于html - golang html 模板不显示任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29524706/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com