| 1 |
--- |
| 2 |
title: ByName |
| 3 |
description: Returns the given menu with its entries sorted by name. |
| 4 |
categories: [] |
| 5 |
keywords: [] |
| 6 |
params: |
| 7 |
functions_and_methods: |
| 8 |
returnType: navigation.Menu |
| 9 |
signatures: [MENU.ByName] |
| 10 |
--- |
| 11 |
|
| 12 |
The `Sort` method returns the given menu with its entries sorted by `name`. |
| 13 |
|
| 14 |
Consider this menu definition: |
| 15 |
|
| 16 |
{{< code-toggle file=hugo >}} |
| 17 |
[[menus.main]] |
| 18 |
name = 'Services' |
| 19 |
pageRef = '/services' |
| 20 |
weight = 10 |
| 21 |
|
| 22 |
[[menus.main]] |
| 23 |
name = 'About' |
| 24 |
pageRef = '/about' |
| 25 |
weight = 20 |
| 26 |
|
| 27 |
[[menus.main]] |
| 28 |
name = 'Contact' |
| 29 |
pageRef = '/contact' |
| 30 |
weight = 30 |
| 31 |
{{< /code-toggle >}} |
| 32 |
|
| 33 |
To sort the entries by `name`: |
| 34 |
|
| 35 |
```go-html-template |
| 36 |
<ul> |
| 37 |
{{ range .Site.Menus.main.ByName }} |
| 38 |
<li><a href="{{ .URL }}">{{ .Name }}</a></li> |
| 39 |
{{ end }} |
| 40 |
</ul> |
| 41 |
``` |
| 42 |
|
| 43 |
Hugo renders this to: |
| 44 |
|
| 45 |
```html |
| 46 |
<ul> |
| 47 |
<li><a href="/about/">About</a></li> |
| 48 |
<li><a href="/contact">Contact</a></li> |
| 49 |
<li><a href="/services/">Services</a></li> |
| 50 |
</ul> |
| 51 |
``` |
| 52 |
|
| 53 |
You can also sort menu entries using the [`sort`][] function. For example, to sort by `name` in descending order: |
| 54 |
|
| 55 |
```go-html-template |
| 56 |
<ul> |
| 57 |
{{ range sort .Site.Menus.main "Name" "desc" }} |
| 58 |
<li><a href="{{ .URL }}">{{ .Name }}</a></li> |
| 59 |
{{ end }} |
| 60 |
</ul> |
| 61 |
``` |
| 62 |
|
| 63 |
When using the sort function with menu entries, specify any of the following keys: `Identifier`, `Name`, `Parent`, `Post`, `Pre`, `Title`, `URL`, or `Weight`. |
| 64 |
|
| 65 |
[`sort`]: /functions/collections/sort/ |