From 85779e72cca281b011cacef5c327621946c82ff6 Mon Sep 17 00:00:00 2001 From: Andrea Zagli Date: Sun, 22 Aug 2021 10:28:39 +0200 Subject: [PATCH] Added customizable table header row template. --- main.go | 50 +++++++++++++++++++++++++++++++++----------------- 1 file changed, 33 insertions(+), 17 deletions(-) diff --git a/main.go b/main.go index 9e684a0..83c060a 100644 --- a/main.go +++ b/main.go @@ -13,17 +13,19 @@ import ( type missingCol func (map[string]interface{}) interface{} type column struct { - name string - title string - align int + Name string + Title string + Align int toCall missingCol } var headerTmpl = "\n{{ . }}\n" +var headerRowTmpl = "\t{{ .Title }}\n" type grid struct { cols []column headerTmpl string + headerRowTmpl string } func (g *grid) addColumn (c column) { @@ -31,12 +33,23 @@ func (g *grid) addColumn (c column) { } func (g *grid) getHeader () string { - tmpl := g.headerTmpl - if tmpl == "" { - tmpl = headerTmpl + htmpl := g.headerTmpl + if htmpl == "" { + htmpl = headerTmpl } - t, err := template.New("header").Parse(tmpl) + t, err := template.New("header").Parse(htmpl) + if err != nil { + fmt.Println(err) + return "" + } + + hrtmpl := g.headerRowTmpl + if hrtmpl == "" { + hrtmpl = headerRowTmpl + } + + tr, err := template.New("headerRow").Parse(hrtmpl) if err != nil { fmt.Println(err) return "" @@ -45,7 +58,10 @@ func (g *grid) getHeader () string { header := "" for i, v := range g.cols { - header += fmt.Sprintf("\t%s\n", v.title) + var b bytes.Buffer + err = tr.Execute(&b, v) + + header += b.String() fmt.Println(i, v) } @@ -63,7 +79,7 @@ func (g *grid) getRowFromMap (m map[string]interface{}) string { ret := "\n" for _, c := range g.cols { - v, ok := m[c.name] + v, ok := m[c.Name] if !ok { if c.toCall != nil { v = c.toCall(m) @@ -71,9 +87,9 @@ func (g *grid) getRowFromMap (m map[string]interface{}) string { } align := "" - if c.align == 1 { + if c.Align == 1 { align = " align='center'" - } else if c.align == 2 { + } else if c.Align == 2 { align = " align='right'" } @@ -96,21 +112,21 @@ func main() { g.headerTmpl = "\n{{ . }}\n" - c := column{name: "id", title: "ID"} + c := column{Name: "id", Title: "ID"} g.addColumn(c) - c = column{name: "name", title: "Name"} + c = column{Name: "name", Title: "Name"} g.addColumn(c) - c = column{name: "surname", title: "Surname"} + c = column{Name: "surname", Title: "Surname"} g.addColumn(c) - c = column{name: "age", title: "Age"} + c = column{Name: "age", Title: "Age"} g.addColumn(c) - c = column{name: "btn", title: "Buttons"} + c = column{Name: "btn", Title: "Buttons"} c.toCall = missing - c.align = 2 + c.Align = 2 g.addColumn(c) fmt.Println (g) -- 2.49.0