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)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?