| 1 |
--- |
| 2 |
title: collections.First |
| 3 |
description: Returns the first N elements of the given slice or string. |
| 4 |
categories: [] |
| 5 |
keywords: [] |
| 6 |
params: |
| 7 |
functions_and_methods: |
| 8 |
aliases: [first] |
| 9 |
returnType: 'any' |
| 10 |
signatures: [collections.First N SLICE|STRING] |
| 11 |
aliases: [/functions/first] |
| 12 |
--- |
| 13 |
|
| 14 |
```go-html-template |
| 15 |
{{ slice "a" "b" "c" | first 1 }} → [a] |
| 16 |
{{ slice "a" "b" "c" | first 2 }} → [a b] |
| 17 |
``` |
| 18 |
|
| 19 |
Given that a string is in effect a read-only slice of bytes, this function can be used to return the specified number of bytes from the beginning of the string: |
| 20 |
|
| 21 |
```go-html-template |
| 22 |
{{ "abc" | first 1 }} → a |
| 23 |
{{ "abc" | first 2 }} → ab |
| 24 |
``` |
| 25 |
|
| 26 |
Note that a _character_ may consist of multiple _bytes_: |
| 27 |
|
| 28 |
```go-html-template |
| 29 |
{{ "Schön" | first 3 }} → Sch |
| 30 |
{{ "Schön" | first 4 }} → Sch\xc3 |
| 31 |
{{ "Schön" | first 5 }} → Schö |
| 32 |
``` |
| 33 |
|
| 34 |
To use the `collections.First` function with a page collection: |
| 35 |
|
| 36 |
```go-html-template |
| 37 |
{{ range first 5 .Pages }} |
| 38 |
{{ .Render "summary" }} |
| 39 |
{{ end }} |
| 40 |
``` |
| 41 |
|
| 42 |
Set `N` to zero to return an empty slice: |
| 43 |
|
| 44 |
```go-html-template |
| 45 |
{{ $emptyPageCollection := first 0 .Pages }} |
| 46 |
``` |
| 47 |
|
| 48 |
Use `first` and [`where`][] together: |
| 49 |
|
| 50 |
```go-html-template |
| 51 |
{{ range where .Pages "Section" "articles" | first 5 }} |
| 52 |
{{ .Render "summary" }} |
| 53 |
{{ end }} |
| 54 |
``` |
| 55 |
|
| 56 |
[`where`]: /functions/collections/where/ |