Golang的HTML模板没有显示任何内容。

huangapple go评论89阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年4月9日 04:26:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/29524706.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定