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