2016-06-17 07:41
浏览 35

Golang HTML中继器

I am trying to create an HTML template that includes a table. Each row in the table should represent a struct I have and include values from that struct.

The only relevant reference I found is this: golang template - how to render templates?

The difference is that I don't know in advance the number of rows in the table, so I need to be able to loop through a dyanmic list of structs I have, and for each such struct populate its values into a template representing a row and add that row to the parent template representing the table.

Can anyone show me how this can be done? Any other approach is also welcome.

图片转代码服务由CSDN问答提供 功能建议

我正在尝试创建一个包含表的HTML模板。 表中的每一行都应代表一个结构体I 具有并包含该结构的值。

我发现的唯一相关参考文献是: golang模板-如何呈现模板?

不同之处在于我事先不知道表中的行数, 因此,我需要能够遍历我拥有的结构的动态列表,并为每个这样的结构将其值填充到表示一行的模板中,并将该行添加到表示该表的父模板中。 \ n

谁能告诉我该怎么做? 也欢迎使用任何其他方法。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongsuiying7773 2016-06-17 08:13

    I think you're just looking for {{range}}, right? E.g.

    package main
    import "log"
    import "os"
    import "html/template"
    type Highscore struct {
        Name  string
        Score int
    func main() {
        const tpl = `<ol>
    {{range .}}
        <li>{{.Name}} - {{.Score}}</li>
        scores := []Highscore{
            Highscore{"Steve", 50},
            Highscore{"Jim", 40},
        scoreTemplate, err := template.New("scores").Parse(tpl)
        if err != nil {
        err = scoreTemplate.Execute(os.Stdout, scores)
        if err != nil {
    点赞 打赏 评论

相关推荐 更多相似问题