HUGO
Menu
GitHub 87548 stars Mastodon

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 函数对菜单条目进行排序时,指定以下任一键:IdentifierNameParentPostPreTitleURLWeight


Last updated: January 1, 0001
Improve this page