From: Andrea Zagli Date: Sun, 22 Aug 2021 08:38:50 +0000 (+0200) Subject: Added customizables row and column templates. X-Git-Url: https://saetta.ns0.it/gitweb?a=commitdiff_plain;h=2c8ffa93a69ff5b913b624a5f8fc370123a69a82;p=zakgrid_go Added customizables row and column templates. --- diff --git a/main.go b/main.go index 83c060a..c5b52ca 100644 --- a/main.go +++ b/main.go @@ -22,10 +22,15 @@ type column struct { var headerTmpl = "\n{{ . }}\n" var headerRowTmpl = "\t{{ .Title }}\n" +var rowTmpl = "\n{{ . }}\n" +var rowColTmpl = "\t{{ .Value }}\n" + type grid struct { cols []column headerTmpl string headerRowTmpl string + rowTmpl string + rowColTmpl string } func (g *grid) addColumn (c column) { @@ -76,7 +81,29 @@ func (g *grid) getHeader () string { } func (g *grid) getRowFromMap (m map[string]interface{}) string { - ret := "\n" + rtmpl := g.rowTmpl + if rtmpl == "" { + rtmpl = rowTmpl + } + + t, err := template.New("row").Parse(rtmpl) + if err != nil { + fmt.Println(err) + return "" + } + + rctmpl := g.rowColTmpl + if rctmpl == "" { + rctmpl = rowColTmpl + } + + tc, err := template.New("rowCol").Parse(rctmpl) + if err != nil { + fmt.Println(err) + return "" + } + + ret := "" for _, c := range g.cols { v, ok := m[c.Name] @@ -86,19 +113,25 @@ func (g *grid) getRowFromMap (m map[string]interface{}) string { } } - align := "" - if c.Align == 1 { - align = " align='center'" - } else if c.Align == 2 { - align = " align='right'" - } + m := make(map[string]interface{}) + m["Name"] = c.Name + m["Align"] = c.Align + m["Value"] = v - ret += fmt.Sprintf("\t%v\n", align, v) + var b bytes.Buffer + err = tc.Execute(&b, m) + + ret += b.String() } - ret += "\n" + var b bytes.Buffer + err = t.Execute(&b, ret) + if err != nil { + fmt.Println(err) + return "" + } - return ret + return b.String() } func missing (row map[string]interface{}) interface{} { @@ -112,6 +145,8 @@ func main() { g.headerTmpl = "\n{{ . }}\n" + g.rowColTmpl = "\t{{ .Value }}\n" + c := column{Name: "id", Title: "ID"} g.addColumn(c)