2

I have an integer having value 5 and i want to loop against it and populate a dropdown as following using range or for loop in html. can any one help me how to do that

<a class="dropdown-item" href="#">1</a>
<a class="dropdown-item" href="#">2</a>
<a class="dropdown-item" href="#">3</a>
<a class="dropdown-item" href="#">4</a>
<a class="dropdown-item" href="#">5</a>

1 Answers1

1

You first need something you can range over, like an array, slice, map, or a channel.

For example in your Go code create a slice of ints ([]int) and assign it to the template data.

items := []int{1, 2, 3, 4, 5}
this.Data["items"] = items

Now inside the template you can range over items like so:

{{range $val := .items}}
<a class="dropdown-item" href="#">{{$val}}</a>
{{end}}

func numSequence(num int) []int {
    out := make([]int, num) // create slice of length equal to num

    for i := range out {
        out[i] = i + 1
    }
    return out
}

fmt.Println(numSequence(5))
// Output: [1, 2, 3, 4, 5]

fmt.Println(numSequence(7))
// Output: [1, 2, 3, 4, 5, 6, 7]

Executable example on Go playgound.

Please note: since playground doesn't support importing of 3rd party packages the example executes the template using the html/template package instead of using the beego framework, but this is ok because beego uses html/template under the hood. Also the hyphen in the example template (-}}) gets rid of whitespace up to the next token, you don't have to use it if you don't want to.

mkopriva
  • 35,176
  • 4
  • 57
  • 71
  • Thanks for the reply, but in my case i have different range of numbers and each case this dropdown will be different. how can i get different arrays based on number – Ravindra Mandalapu Nov 14 '17 at 11:00
  • In Go you can use [for loops](https://golang.org/ref/spec#For_statements) and [append](https://golang.org/ref/spec#Appending_and_copying_slices) to create slices of any length. Or actually you don't even have to use appned if you know the number of items, just initialize your slice to the correct length and then use indexes to set the slice element values. – mkopriva Nov 14 '17 at 11:03
  • @RavindraMandalapu I've added an example of how to create a sequence of numbers. – mkopriva Nov 14 '17 at 11:14
  • @RavindraMandalapu I've now also added a playground link with an executable example. – mkopriva Nov 14 '17 at 11:29