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