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.
This section is empty.
This section is empty.
This section is empty.
Template is the representation of a template.
// 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
New initializes a Template.
Execute applies the parsed template to the input and writes result to the writer the template was initialized with.
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.
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.
// 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
Parse the given template string for use with Execute.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4