转到模板:范围超过字符串

Is there any way to range over a string in Go templates (that is, from the code in the template itself, not from native Go)? It doesn't seem to be supported directly (The value of the pipeline must be an array, slice, map, or channel.), but is there some hack like splitting the string into an array of single-character strings or something?

Note that I am unable to edit any go source: I'm working with a compiled binary here. I need to make this happen from the template code alone.

You can use FuncMap to split string into characters.

package main

import (
    "text/template"
    "log"
    "os"
)

func main() {
    tmpl, err := template.New("foo").Funcs(template.FuncMap{
        "to_runes": func(s string) []string {
            r := []string{}
            for _, c := range []rune(s) {
                r = append(r, string(c))
            }
            return r
        },
    }).Parse(`{{range . | to_runes }}[{{.}}]{{end}}`)
    if err != nil {
        log.Fatal(err)
    }


    err = tmpl.Execute(os.Stdout, "hello world")
    if err != nil {
        log.Fatal(err)
    }
}

This should be:

[h][e][l][l][o][ ][w][o][r][l][d]