简体   繁体   中英

Golang - HTML Templating - Range limit

I have a slice which I am printing to an html file in go:

<ul>
{{range .arr}}
    <li>{{.}}</li>
{{end}}
</ul>

If len(arr) > 5 , how do I print only the first 5 elements of the slice?

First off, I should mention that if you're passing an array to the template, you're almost certainly doing something weird. Arrays are relatively rarely used in Go. Typically, you would use a slice .

The easiest way would be to pass a slice of the first 5 elements of the array when running the template.

If you need the full input in the template for some reason, you could define a function for taking slices, something like this:

func mkslice(a []string, start, end int) []string {
    return a[start:end]
}

(see documentation for how to attach functions to templates )

And the template:

{{range mkslice .arr 0 5}}
<li>{{.}}</li>
{{end}}

You could also use a form of the range action with an index.

{{range $i, $val := .arr}}
{{if lt $i 5}}<li>{{$val}}</li>{{end}}
{{end}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM