doushuangdui5419 2016-06-17 07:41
浏览 36
已采纳

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.

  • 写回答

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>
    {{end}}
    </ol>
    `
        scores := []Highscore{
            Highscore{"Steve", 50},
            Highscore{"Jim", 40},
        }
    
        scoreTemplate, err := template.New("scores").Parse(tpl)
        if err != nil {
            log.Fatal(err)
        }
    
        err = scoreTemplate.Execute(os.Stdout, scores)
        if err != nil {
            log.Fatal(err)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改