HUGO
Menu
GitHub 87548 stars Mastodon

PageRef

返回給定菜單項的 pageRef 屬性。

Syntax

MENUENTRY.PageRef

Returns

string

此方法的用例很少見。 在幾乎所有情況下,您應該使用 URL 方法。

解釋

如果在站點配置中 定義菜單條目 時指定了 pageRef 屬性,Hugo 在渲染條目時會查找匹配的頁面。

如果找到匹配的頁面:

如果未找到匹配的頁面:

  • URL 方法返回條目的 url 屬性(如果設置),否則返回空字符串
  • Page 方法返回 nil
  • Page 對象上的 HasMenuCurrentIsMenuCurrent 方法返回 false

在幾乎所有情況下,您應該使用 URL 方法。

示例

此示例是虛構的。

在幾乎所有情況下,您應該使用 URL 方法。

考慮此內容結構:

content/
├── products.md
└── _index.md

以及此菜單定義:

menus:
  main:
  - name: Products
    pageRef: /products
    weight: 10
  - name: Services
    pageRef: /services
    weight: 20
[menus]
  [[menus.main]]
    name = 'Products'
    pageRef = '/products'
    weight = 10
  [[menus.main]]
    name = 'Services'
    pageRef = '/services'
    weight = 20
{
   "menus": {
      "main": [
         {
            "name": "Products",
            "pageRef": "/products",
            "weight": 10
         },
         {
            "name": "Services",
            "pageRef": "/services",
            "weight": 20
         }
      ]
   }
}

使用此模板代碼:

layouts/_partials/menu.html
<ul>
  {{ range .Site.Menus.main }}
    <li><a href="{{ .URL }}">{{ .Name }}</a></li>
  {{ end }}
</ul>

Hugo 渲染此 HTML:

<ul>
  <li><a href="/products/">Products</a></li>
  <li><a href="">Services</a></li>
</ul>

在上面請注意,第二個 anchor 元素的 href 屬性為空,因為 Hugo 無法找到 “services” 頁面。

使用此模板代碼:

layouts/_partials/menu.html
<ul>
  {{ range .Site.Menus.main }}
    <li><a href="{{ or .URL .PageRef }}">{{ .Name }}</a></li>
  {{ end }}
</ul>

Hugo 渲染此 HTML:

<ul>
  <li><a href="/products/">Products</a></li>
  <li><a href="/services">Services</a></li>
</ul>

在上面請注意,Hugo 使用站點配置中定義的 pageRef 屬性填充第二個 anchor 元素的 href 屬性,因為模板代碼回退到 PageRef 方法。


Last updated: January 1, 0001
Improve this page