ByWeight
返回給定菜單,其條目按權重、然後按名稱、然後按標識符排序。
Syntax
MENU.ByWeight
Returns
navigation.Menu
ByWeight 方法返回給定菜單,其條目按 weight、然後按 name、然後按 identifier 排序。這是默認排序順序。
考慮以下菜單定義:
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>在上面的菜單定義中,請注意當兩個或更多菜單條目具有相同的名稱,或使用翻譯表本地化名稱時,identifier 屬性才是必需的。
您也可以使用 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。