【问题标题】:How to convert a map to html table in Go如何在 Go 中将地图转换为 html 表格
【发布时间】:2022-01-14 19:15:05
【问题描述】:

我是围棋新手并正在练习,请您帮忙将地图转换为 GO 中的 html 表格吗? 我有一个函数可以从一些休息端点获取一些数据,并根据我从端点返回的结果返回一个大小可以变化的地图。

type color struct {
   blue int
   red  int
}
func fetchData() map[string]map[string]colour {}

打印出这个函数的输出看起来像这样,但每次列的数量或多或少都会有所不同

map[joe:map[alex: {3 6} may:{2 6}] jena:map[fred: {1 2}]]

我想要一个这样的 html 表格:

Teacher Student Blue Pens Red Pens
joe alex 3 6
may 2 6
jena fred 1 2

【问题讨论】:

    标签: html css dictionary go


    【解决方案1】:

    我认为最简单的方法是使用html/template 包。 text/template 的文档解释了语法,以防您不熟悉模板引擎。

    像这样(playground link):

    package main
    
    import (
        "html/template"
        "os"
    )
    
    const tplStr = `<table>
        <thead>
            <tr>
                <th>Teacher</th>
                <th>Student</th>
                <th>Blue Pens</th>
                <th>Red Pens</th>
            </tr>
        </thead>
        <tbody>
            {{range $teacher, $rows := . }}
                {{ $first := true }}
                {{ range $student, $colors := . }}
                <tr>
                    <td>{{ if $first }}{{ $first = false }}{{ $teacher }}{{ end }}</td>
                    <td>{{ $student }}</td>
                    <td>{{ $colors.Blue }}</td>
                    <td>{{ $colors.Red }}</td>
                </tr>
                {{ end }}
            {{ end }}
        </tbody>
    </table>`
    
    type color struct {
        Blue int
        Red  int
    }
    
    func fetchData() map[string]map[string]color {
        return map[string]map[string]color{
            "joe": {
                "alex": {
                    Blue: 3,
                    Red:  6,
                },
                "may": {
                    Blue: 2,
                    Red:  6,
                },
            },
            "jena": {
                "fred": color{
                    Blue: 1,
                    Red:  2,
                },
            },
        }
    }
    
    func main() {
        tpl, err := template.New("table").Parse(tplStr)
        if err != nil {
            panic(err)
        }
    
        err = tpl.Execute(os.Stdout, fetchData())
        if err != nil {
            panic(err)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-07-17
      • 1970-01-01
      • 2021-09-21
      • 2022-12-03
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      • 2010-11-27
      相关资源
      最近更新 更多