ByWeight
Syntax
MENU.ByWeight
Returns
navigation.Menu
ByWeight
方法返回给定的菜单,其条目按 weight
排序,然后按 name
排序,最后按 identifier
排序。这是默认的排序顺序。
考虑以下菜单定义:
hugo.
menus:
main:
- identifier: about
name: About
pageRef: /about
weight: 20
- identifier: services
name: Services
pageRef: /services
weight: 10
- identifier: contact
name: Contact
pageRef: /contact
weight: 30
[menus]
[[menus.main]]
identifier = 'about'
name = 'About'
pageRef = '/about'
weight = 20
[[menus.main]]
identifier = 'services'
name = 'Services'
pageRef = '/services'
weight = 10
[[menus.main]]
identifier = 'contact'
name = 'Contact'
pageRef = '/contact'
weight = 30
{
"menus": {
"main": [
{
"identifier": "about",
"name": "About",
"pageRef": "/about",
"weight": 20
},
{
"identifier": "services",
"name": "Services",
"pageRef": "/services",
"weight": 10
},
{
"identifier": "contact",
"name": "Contact",
"pageRef": "/contact",
"weight": 30
}
]
}
}
要按 weight
、 name
和 identifier
的顺序排序条目:
<ul>
{{ range .Site.Menus.main.ByWeight }}
<li><a href="{{ .URL }}">{{ .Name }}</a></li>
{{ end }}
</ul>
Hugo 将其渲染为:
<ul>
<li><a href="/services/">Services</a></li>
<li><a href="/about/">About</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
您还可以使用 sort
函数对菜单条目进行排序。例如,要按 weight
降序排序:
<ul>
{{ range sort .Site.Menus.main "Weight" "desc" }}
<li><a href="{{ .URL }}">{{ .Name }}</a></li>
{{ end }}
</ul>
当使用 sort
函数处理菜单条目时,请指定以下任何键: Identifier
、 Name
、 Parent
、 Post
、 Pre
、 Title
、 URL
或 Weight
。