Debian Codegraph @

template.go

raw
1 package tblfmt
2
3 import (
4 "fmt"
5 "html"
6 "io"
7 "strings"
8 )
9
10 // Template is template data.
11 type Template struct {
12 Attributes string
13 Headers []*Value
14 Rows [][]*Value
15 SkipHeader bool
16 Title *Value
17 }
18
19 // WriteHTMLTo writes simple HTML output to the writer.
20 func WriteHTMLTo(w io.Writer, tpl *Template) error {
21 // {{ $headers := .Headers }}{{ $rows := .Rows }}<table{{ .Attributes | attr }}>
22 // <caption>{{ .Title }}</caption>
23 // <thead>
24 // <tr>{{ range $i, $h := $headers }}
25 // <th align="{{ $h.Align.String | toLower }}">{{ $h }}</th>{{ end }}
26 // </tr>
27 // </thead>
28 // <tbody>{{ range $i, $r := $rows }}
29 // <tr>{{ range $j, $c := $r }}
30 // <td align="{{ $c.Align.String | toLower }}">{{ $c }}</td>{{ end }}
31 // </tr>{{ end }}
32 // </tbody>
33 // </table>
34 fmt.Fprint(w, "<table")
35 if len(tpl.Attributes) != 0 {
36 fmt.Fprint(w, "", tpl.Attributes)
37 }
38 fmt.Fprintf(w, ">\n <caption>%s</caption>\n <thead>\n <tr>\n", tpl.Title)
39 for _, h := range tpl.Headers {
40 fmt.Fprintf(w, " <th align=%q>%s</th>\n", strings.ToLower(h.Align.String()), html.EscapeString(h.String()))
41 }
42 fmt.Fprint(w, " </tr>\n </thead>\n <tbody>")
43 for _, r := range tpl.Rows {
44 fmt.Fprint(w, "\n <tr>")
45 for _, c := range r {
46 fmt.Fprintf(w, "\n <td align=%q>%s</td>", strings.ToLower(c.Align.String()), html.EscapeString(c.String()))
47 }
48 fmt.Fprint(w, "\n </tr>")
49 }
50 fmt.Fprintln(w, "\n </tbody>\n</table>")
51 return nil
52 }
53
54 // WriteAsciidocTo writes simple asciidoc output to the writer.
55 func WriteAsciidocTo(w io.Writer, tpl *Template) error {
56 // {{ $headers := .Headers }}{{ $rows := .Rows }}[%header]{{ if .Title.Buf }}
57 // .{{ .Title }}{{ end }}
58 // |==={{ range $i, $h := $headers }}
59 // |{{ $h }}{{ end }}{{ range $i, $r := $rows }}
60 // {{ range $j, $c := $r }}|{{ $c }}{{ end }}{{ end }}
61 // |===
62 fmt.Fprint(w, "[%header]")
63 if s := tpl.Title.String(); s != "" {
64 fmt.Fprintf(w, "\n%s", tpl.Title.String())
65 }
66 fmt.Fprint(w, "\n|===")
67 for _, h := range tpl.Headers {
68 fmt.Fprintf(w, "\n|%s", h)
69 }
70 for _, r := range tpl.Rows {
71 fmt.Fprintln(w)
72 for _, c := range r {
73 fmt.Fprintf(w, "|%s", c)
74 }
75 }
76 fmt.Fprintln(w, "\n|===")
77 return nil
78 }
79
80 // WriteVerticalTo writes simple vertical output to the writer.
81 func WriteVerticalTo(w io.Writer, tpl *Template) error {
82 // {{ $headers := .Headers }}{{ range $i, $r := .Rows }}*************************** {{ inc $i }}. row ***************************{{ range $j, $c := $r }}
83 // {{ index $headers $j }}: {{ $c }}{{ end }}
84 // {{ end -}}
85 const divider = `***************************`
86 for i, r := range tpl.Rows {
87 fmt.Fprintf(w, "%s %d. %s\n", divider, i+1, divider)
88 for j, c := range r {
89 fmt.Fprintf(w, "%s: %s\n", tpl.Headers[j], c)
90 }
91 }
92 return nil
93 }