如何在 Go 中将地图转换为 html 表

fla*_*s33 1 html css dictionary go

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

type color struct {
   blue int
   red  int
}
func fetchData() map[string]map[string]colour {}
Run Code Online (Sandbox Code Playgroud)

打印出该函数的输出看起来像这样,但每次都会因列的增加或减少而变化

map[joe:map[alex: {3 6} may:{2 6}] jena:map[fred: {1 2}]]
Run Code Online (Sandbox Code Playgroud)

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

老师 学生 蓝笔 红笔
亚历克斯 3 6
可能 2 6
耶拿 弗雷德 1 2

Dyl*_*ink 5

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

像这样(游乐场链接):

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)
    }
}
Run Code Online (Sandbox Code Playgroud)