Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range over string slice in golang template

I have a struct that contains a slice of type string like the following.

 type Data struct {
      DataFields []string
 }

Within my html template file I would like to range over the string slice. However, the individual fields are just strings without any struct name. How can I loop over a slice that contains a simple type such as string, int, etc?

like image 755
JetThomas Avatar asked Jan 12 '19 01:01

JetThomas


2 Answers

Use . to refer to a simple values like a string, int, etc.

 {{range .DataFields}}{{.}}{{end}}

Run it on the Playground.

You can also assign to a template variable as in {{range $v := .DataFields}}{{$v}}{{end}}, but that's extra work. Embrace the ..

like image 121
Bayta Darell Avatar answered Nov 16 '22 15:11

Bayta Darell


Or assign it to a variable, similar to a normal Go range clause:

 {{range $element := .DataFields}} {{$element}} {{end}}

Run it on the Playground

From the docs for text/template (serves as interface docs for html/template):

{{range pipeline}} T1 {{end}}
    The value of the pipeline must be an array, slice, map, or channel.
    If the value of the pipeline has length zero, nothing is output;
    otherwise, dot is set to the successive elements of the array,
    slice, or map and T1 is executed. If the value is a map and the
    keys are of basic type with a defined order ("comparable"), the
    elements will be visited in sorted key order.

...

A pipeline inside an action may initialize a variable to capture the result. The initialization has syntax

$variable := pipeline

...

If a "range" action initializes a variable, the variable is set to the successive elements of the iteration. Also, a "range" may declare two variables, separated by a comma:

range $index, $element := pipeline

in which case $index and $element are set to the successive values of the array/slice index or map key and element, respectively. Note that if there is only one variable, it is assigned the element; this is opposite to the convention in Go range clauses.

(bold portions emphasized by me)

like image 28
blobdon Avatar answered Nov 16 '22 13:11

blobdon