DJBrunelle
DJBrunelle

Reputation: 25

Iterate over a variable number of items in a template slice

After searching through a fair amount of documentation and forum topics, I have not found a solution to iterating over a variable number of items in a slice using the go template engine.

My situation is as follows:

I have set up 3 structs, of which I'm passing User to an html page

type User struct {
    Name    string 
    Foos    []Foo
}

type Foo struct {
    Name        string 
    Description string 
    Bars     []Bar
}

type Bar struct {
    Name    string 
}

I would like to iterate over only the first 3 Bars in each Foo from User, but I also need to account for the possibility of each Bar containing less than 3 items.

The following will iterate over all Bars, but I only want to list up to 3, of course only listing 1 or 2 if there are only that many in the slice.

{{range .Foos}}
<div>
    <h3>{{.Name}}</h3>
    <h4>{{.Description}}</h4>
    <ol>
        {{range .Bars}}
        <li> {{.Name}} </li>
        {{end}}
    </ol>
</div>
{{end}}

Is it possible to achieve this with the go template engine? Any help would be appreciated.

Upvotes: 2

Views: 929

Answers (1)

eugenioy
eugenioy

Reputation: 12383

As stated in the comments, you can trim the slice before sending it to the template, but that might be a problem if it is part of a nested struct that you need to continue using afterwards.

Another option could be to avoid processing more than 3 elements with an if value on the index inside the loop:

{{range $i, $val := .Bars}}
    {{if le $i 3}}<li> {{$val.Name}} </li>{{end}}
{{end}}

Upvotes: 2

Related Questions