diff --git a/pkg/export/template.go b/pkg/export/template.go index 57004da73..bc0986d78 100644 --- a/pkg/export/template.go +++ b/pkg/export/template.go @@ -56,7 +56,15 @@ func (t *Template) parseTemplate(tpl string) (*template.Template, error) { "join": templateJoin, "tablerow": t.tableRow, "tablerender": t.tableRender, - "truncate": text.Truncate, + "truncate": func(maxWidth int, v interface{}) (string, error) { + if v == nil { + return "", nil + } + if s, ok := v.(string); ok { + return text.Truncate(maxWidth, s), nil + } + return "", fmt.Errorf("invalid value; expected string, got %T", v) + }, } if !t.io.ColorEnabled() { diff --git a/pkg/export/template_test.go b/pkg/export/template_test.go index fc44a1275..5167f7cc9 100644 --- a/pkg/export/template_test.go +++ b/pkg/export/template_test.go @@ -263,6 +263,38 @@ func Test_executeTemplate(t *testing.T) { }, wantW: "This is a ...", }, + { + name: "truncate with JSON null", + args: args{ + json: strings.NewReader(`{}`), + template: `{{ truncate 13 .title }}`, + }, + wantW: "", + }, + { + name: "truncate with piped JSON null", + args: args{ + json: strings.NewReader(`{}`), + template: `{{ .title | truncate 13 }}`, + }, + wantW: "", + }, + { + name: "truncate with piped JSON null in parenthetical", + args: args{ + json: strings.NewReader(`{}`), + template: `{{ (.title | truncate 13) }}`, + }, + wantW: "", + }, + { + name: "truncate invalid type", + args: args{ + json: strings.NewReader(`{"title": 42}`), + template: `{{ (.title | truncate 13) }}`, + }, + wantErr: true, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) {