Search code examples
stringgogo-templates

How do I access substrings (s[:2]) in Go templates?


Similar to Go templates: How do I access array item (arr[2]) in templates?
How do I directly access substrings (e.g. s[:2]) in Go templates?

Whenever I do this I get "bad character U+005B '['"

{{ .s[:2] }}

Solution

  • You may use the slice template function on strings too (it was added in Go 1.13):

    Template functions:

    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.
    

    For example:

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

    This will output (try it on the Go Playground):

    ab
    

    Don't forget that Go strings store the UTF-8 encoded byte sequence, and indexing and slicing strings uses the byte index (not the rune index). This matters when the string contains multi-byte runes, like in this example:

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

    This will output a single rune (try it on the Go Playground):