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.