Search code examples
stringgotemplatesjiraslice

Q: go-jira: slice is not slicing strings in templates


I try to get the date (2020-03-09) from "2020-03-09T08:09:40.000+0000" with this template line:

... [Ticket:{{- .key -}}:{{ .fields.resolution.name }}] starts {{ slice .fields.created 0 10 }} and ends {{ slice .fields.resolutiondate 0 10 }} ...

--> Invalid Usage: template: gojira:7:62: executing "gojira" at <slice .fields.created 0 10>: error calling slice: list should be type of slice or array but string

Documentations says:

slice
slice returns the result of slicing its first argument by the remaining arguments. Thus "slice x 1 2" is, in Go syntax, x[1:2], while "slice x" is x[:], "slice x 1" is x[1:], and "slice x 1 2 3" is x[1:2:3]. The first argument must be a string, slice, or array.

Here the complete template I use with go-jira:

@startgantt
{{ range .issues -}} 
[Ticket:{{- .key -}}:{{ .fields.resolution.name }}] starts {{ slice .fields.created 0 10  }} and ends {{ slice .fields.resolutiondate 0 10 }}
[Ticket:{{- .key -}}:{{ .fields.resolution.name }}] is colored Yellow
{{ if (and .fields.customfield_11202 .fields.customfield_11203) -}}
[Planned:{{- .key -}}:{{ .fields.resolution.name }}] starts {{ .fields.customfield_11202 }} and ends {{ .fields.customfield_11203 }}
[Planned:{{- .key -}}:{{ .fields.resolution.name }}] is colored LightBlue
{{ end -}}
{{ end -}}
@endgantt

Solution

  • The slice function was added in Go 1.13, so if you're using Go 1.10.4 as you indicated in your comments, this function is not known to the parsing engine. Go-jira might add a function with this name, but that may not support slicing strings.

    Best is if you upgrade to Go 1.13 or newer, and this slice function will be ready to slice your strings as can be seen in this example:

    t := template.Must(template.New("").Parse(`{{slice . 1 3}}`))
    if err := t.Execute(os.Stdout, "012345"); err != nil {
        panic(err)
    }
    

    Which outputs (try it on the Go Playground):

    12