【问题标题】:golang html template doesn't display anythinggolang html模板不显示任何内容
【发布时间】:2015-04-08 20:26:29
【问题描述】:

我有这段用于 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}}

【问题讨论】:

    标签: html templates go


    【解决方案1】:

    Page.test 字段未导出,它以小写字母开头。模板引擎(就像其他一切一样)只能访问导出的字段。

    改成:

    type Page struct {
        Test [3]Person
        Test2 string
    }
    

    以及您引用它的所有其他地方,例如p:= Page{Test: a}。并且在模板中:

    {{range .Test}}
        item
    {{end}}
    

    还有:永远不要忽略检查错误!你至少可以做的是恐慌:

    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 上试用。

    【讨论】:

    • 成功了,非常感谢。我实际上错过了那个字段导出的东西,我在哪里可以读到它?
    • @Nickl 在Language specification: Exported Identifiers。模板引擎位于不同的包 (html/template) 中,因此规则也适用于它。
    猜你喜欢
    • 2020-04-17
    • 2022-11-15
    • 2021-06-12
    • 2012-02-20
    • 2016-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多