ByWeight

ByWeight 方法會傳回指定的選單,並依據 weightname,最後依 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 函數排序選單項目時,可指定以下任一鍵值:IdentifierNameParentPostPreTitleURLWeight