Home > Mobile >  How to convert a map to html table in Go
How to convert a map to html table in Go

Time:01-15

I'm newbie in Go and practicing, could you please help to convert a map to an html table in GO? I have a function that fetches some data from some rest end points and return a map that can vary in size based on the result I get back from the endpoints.

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

printing out the output of this function looks like this but can vary each time with more or less columns

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

I would to have a html table like this:

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

CodePudding user response:

The easiest way in my opinion is to use the html/template package. The docs of text/template explain the syntax, in case you are not familiar with the templating engine.

Like so (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)
    }
}
  •  Tags:  
  • Related