Documentation ¶
Overview ¶
Package template facilitates processing of JSON strings using Go templates. Provides additional functions not available using basic Go templates, such as coloring, and table rendering.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Template ¶
type Template struct {
// contains filtered or unexported fields
}
Template is the representation of a template.
Example ¶
// Information about the terminal can be obtained using the [pkg/term] package. colorEnabled := true termWidth := 14 json := strings.NewReader(heredoc.Doc(`[ {"number": 1, "title": "One"}, {"number": 2, "title": "Two"} ]`)) template := "HEADER\n\n{{range .}}{{tablerow .number .title}}{{end}}{{tablerender}}\nFOOTER" tmpl := New(os.Stdout, termWidth, colorEnabled) if err := tmpl.Parse(template); err != nil { log.Fatal(err) } if err := tmpl.Execute(json); err != nil { log.Fatal(err) }
Output: HEADER 1 One 2 Two FOOTER
func (*Template) Execute ¶
Execute applies the parsed template to the input and writes result to the writer the template was initialized with.
func (*Template) Flush ¶
Flush writes any remaining data to the writer. This is mostly useful when a templates uses the tablerow function but does not include the tablerender function at the end. If a template did not use the table functionality this is a noop.
func (*Template) Funcs ¶
Funcs adds the elements of the argument map to the template's function map. It must be called before the template is parsed. It is legal to overwrite elements of the map including default functions. The return value is the template, so calls can be chained.
Example ¶
// Information about the terminal can be obtained using the [pkg/term] package. colorEnabled := true termWidth := 14 json := strings.NewReader(heredoc.Doc(`[ {"num": 1, "thing": "apple"}, {"num": 2, "thing": "orange"} ]`)) template := "{{range .}}* {{pluralize .num .thing}}\n{{end}}" tmpl := New(os.Stdout, termWidth, colorEnabled) tmpl.Funcs(map[string]interface{}{ "pluralize": func(fields ...interface{}) (string, error) { if l := len(fields); l != 2 { return "", fmt.Errorf("wrong number of args for pluralize: want 2 got %d", l) } var ok bool var num float64 var thing string if num, ok = fields[0].(float64); !ok && num == float64(int(num)) { return "", fmt.Errorf("invalid value; expected int") } if thing, ok = fields[1].(string); !ok { return "", fmt.Errorf("invalid value; expected string") } return text.Pluralize(int(num), thing), nil }, }) if err := tmpl.Parse(template); err != nil { log.Fatal(err) } if err := tmpl.Execute(json); err != nil { log.Fatal(err) }
Output: * 1 apple * 2 oranges