Merge commit '35dec7c96f7ee3eb17dd444f7067f0c776fb56ae'

This commit is contained in:
Bjørn Erik Pedersen
2023-12-04 15:24:01 +01:00
810 changed files with 24147 additions and 7766 deletions

View File

@@ -1,53 +1,36 @@
---
title: collections.First
linkTitle: first
description: Slices an array to the first N elements.
categories: [functions]
description: Returns the given collection, limited to the first N elements.
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [first]
related:
- functions/collections/After
- functions/collections/Last
returnType: any
signatures: [collections.First LIMIT COLLECTION]
relatedFunctions:
- collections.After
- collections.First
- collections.Last
signatures: [collections.First N COLLECTION]
aliases: [/functions/first]
---
`first` works in a similar manner to the [`limit` keyword in
SQL][limitkeyword]. It reduces the array to only the `first N`
elements. It takes the array and number of elements as input.
`first` takes two arguments:
1. `number of elements`
2. `array` *or* `slice of maps or structs`
{{< code file="layout/_default/section.html" >}}
{{ range first 10 .Pages }}
{{ .Render "summary" }}
```go-html-template
{{ range first 5 .Pages }}
{{ .Render "summary" }}
{{ end }}
{{< /code >}}
```
*Note: Exclusive to `first`, LIMIT can be '0' to return an empty array.*
Set `N` to zero to return an empty collection.
## `first` and `where` Together
```go-html-template
{{ $emptyPageCollection := first 0 .Pages}}
```
Using `first` and [`where`] together can be very
powerful. Below snippet gets a list of posts only from [main
sections], sorts it by the `title` parameter, and then
ranges through only the first 5 posts in that list:
Use `first` and [`where`] together.
{{< code file="first-and-where-together.html" >}}
{{ range first 5 (where site.RegularPages "Type" "in" site.Params.mainSections).ByTitle }}
{{ .Content }}
```go-html-template
{{ range where .Pages "Section" "articles" | first 5 }}
{{ .Render "summary" }}
{{ end }}
{{< /code >}}
```
[limitkeyword]: https://www.techonthenet.com/sql/select_limit.php
[`where`]: /functions/collections/where
[main sections]: /functions/collections/where#mainsections