# ByName
> 返回给定菜单，其条目按 name 排序。
- 官方英文原文：https://gohugo.io/methods/menu/byname/
- 本页规范地址：https://hugozh.cn/methods/menu/byname/
- 最近更新：2026-10-02
- 最后提交：912b1d3 chore(site): 添加 static/CNAME（hugozh.cn），供 GitHub Pages 等平台绑定自定义域名
- 签名：MENU.ByName
- 返回类型：navigation.Menu
- 站点：Hugo 中文文档（https://hugozh.cn/）· 社区维护的非官方中文翻译，如有出入以官方英文原文为准

---
`Sort` 方法返回给定菜单，其条目按 `name` 排序。

请看下面的菜单定义：

```toml
[[menus.main]]
name = 'Services'
pageRef = '/services'
weight = 10

[[menus.main]]
name = 'About'
pageRef = '/about'
weight = 20

[[menus.main]]
name = 'Contact'
pageRef = '/contact'
weight = 30
```

要按 `name` 排序条目：

```go-html-template
<ul>
  {{ range .Site.Menus.main.ByName }}
    <li><a href="{{ .URL }}">{{ .Name }}</a></li>
  {{ end }}
</ul>
```

Hugo 渲染结果为：

```html
<ul>
  <li><a href="/about/">About</a></li>
  <li><a href="/contact">Contact</a></li>
  <li><a href="/services/">Services</a></li>
</ul>
```

也可以使用 [`sort`][] 函数对菜单条目排序。例如按 `name` 降序排序：

```go-html-template
<ul>
  {{ range sort .Site.Menus.main "Name" "desc" }}
    <li><a href="{{ .URL }}">{{ .Name }}</a></li>
  {{ end }}
</ul>
```

对菜单条目使用 sort 函数时，可指定以下任意键：`Identifier`、`Name`、`Parent`、`Post`、`Pre`、`Title`、`URL` 或 `Weight`。

[`sort`]: /functions/collections/sort/

