duanbo2048 2015-04-08 20:26
浏览 370
已采纳

golang html模板不显示任何内容

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条回答 默认 最新

  • dongyata3336 2015-04-08 20:29
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?