p_mcp
p_mcp

Reputation: 2801

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?

Upvotes: 10

Views: 4802

Answers (1)

Staven
Staven

Reputation: 3165

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}}

Upvotes: 14

Related Questions