视图模板中的Beego范围[重复]

This question already has an answer here:

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>
</div>

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.