Search code examples
gogo-templates

Range over string or string array in Go template


I am writing a Go template that uses consecutive alpha characters. As a simple example:

{{ range $i, $e := until 2 }}
{{ range $a := .[]string{"a", "b", "c"} }}
<p>{{ $e }}{{ $a }}. Sample Text</p>
{{ end }}
<br>
{{ end }}

Should yield:

<p>0a. Sample Text</p>
<p>0b. Sample Text</p>
<p>0c. Sample Text</p>
<br>
<p>1a. Sample Text</p>
<p>1b. Sample Text</p>
<p>1c. Sample Text</p>
<br>

The above code would work if go templates let you define arrays this way inside the template. I would need something similar to this, or the answer here, with the exception that I am not able to write my own functions. I am using this for another piece of software that lets me write go templates, but I cannot modify the go code itself, meaning no passing variables either.

Am I asking the impossible?


Solution

  • It looks like the template host uses Sprig. Use the list function from Sprig.

    {{ range $i, $e := until 2 }}
    {{ range $a := list "a" "b" "c"}}
    <p>{{ $e }}{{ $a }}. Sample Text</p>
    {{- end}}
    <br>
    {{- end}}
    

    Run an example on the playground.