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 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)
  • ¥66 比特币地址如何生成taproot地址
  • ¥20 数学建模数学建模需要
  • ¥15 关于#lua#的问题,请各位专家解答!
  • ¥15 什么设备可以研究OFDM的60GHz毫米波信道模型
  • ¥15 不知道是该怎么引用多个函数片段
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥15 隐藏系统界面pdf的打印、下载按钮