Skip to content

Commit c24b62f

Browse files
committed
templates: add formatJSON func
Move the function used to format as JSON to a separate function instead of definining it inline. Signed-off-by: Sebastiaan van Stijn <[email protected]>
1 parent be97096 commit c24b62f

File tree

1 file changed

+14
-12
lines changed

1 file changed

+14
-12
lines changed

templates/templates.go

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -13,18 +13,7 @@ import (
1313
// basicFunctions are the set of initial
1414
// functions provided to every template.
1515
var basicFunctions = template.FuncMap{
16-
"json": func(v any) string {
17-
buf := &bytes.Buffer{}
18-
enc := json.NewEncoder(buf)
19-
enc.SetEscapeHTML(false)
20-
err := enc.Encode(v)
21-
if err != nil {
22-
panic(err)
23-
}
24-
25-
// Remove the trailing new line added by the encoder
26-
return strings.TrimSpace(buf.String())
27-
},
16+
"json": formatJSON,
2817
"split": strings.Split,
2918
"join": strings.Join,
3019
"title": strings.Title, //nolint:nolintlint,staticcheck // strings.Title is deprecated, but we only use it for ASCII, so replacing with golang.org/x/text is out of scope
@@ -103,3 +92,16 @@ func truncateWithLength(source string, length int) string {
10392
}
10493
return source[:length]
10594
}
95+
96+
func formatJSON(v any) string {
97+
buf := &bytes.Buffer{}
98+
enc := json.NewEncoder(buf)
99+
enc.SetEscapeHTML(false)
100+
err := enc.Encode(v)
101+
if err != nil {
102+
panic(err)
103+
}
104+
105+
// Remove the trailing new line added by the encoder
106+
return strings.TrimSpace(buf.String())
107+
}

0 commit comments

Comments
 (0)