HUGO
Menu
GitHub 87548 stars Mastodon

GetPage

返回給定路徑的頁面對象。

Syntax

SITE.GetPage PATH

Returns

page.Page

GetPage 方法也可在 Page 對象上使用,允許您指定相對於當前頁面的路徑。請參閱 詳情

當在 Site 對象上使用 GetPage 方法時,指定相對於 content 目錄的路徑。

如果 Hugo 無法將路徑解析為頁面,該方法返回 nil。

考慮此內容結構:

content/
├── works/
│   ├── paintings/
│   │   ├── _index.md
│   │   ├── starry-night.md
│   │   └── the-mona-lisa.md
│   ├── sculptures/
│   │   ├── _index.md
│   │   ├── david.md
│   │   └── the-thinker.md
│   └── _index.md
└── _index.md

主頁 模板:

layouts/home.html
{{ with .Site.GetPage "/works/paintings" }}
  <ul>
    {{ range .Pages }}
      <li>{{ .Title }} by {{ .Params.artist }}</li>
    {{ end }}
  </ul>
{{ end }}

渲染為:

<ul>
  <li>Starry Night by Vincent van Gogh</li>
  <li>The Mona Lisa by Leonardo da Vinci</li>
</ul>

要獲取常規頁面而不是節頁面:

layouts/home.html
{{ with .Site.GetPage "/works/paintings/starry-night" }}
  {{ .Title }} → Starry Night
  {{ .Params.artist }} → Vincent van Gogh
{{ end }}

多語言項目

使用多語言項目時,Site 對象上的 GetPage 方法將給定路徑解析為當前語言中的頁面。

要從不同語言獲取頁面,請查詢 Sites 對象:

{{ with where .Site.Sites "Language.Lang" "eq" "de" }}
  {{ with index . 0 }}
    {{ with .GetPage "/works/paintings/starry-night" }}
      {{ .Title }} → Sternenklare Nacht
    {{ end }}
  {{ end }}
{{ end }}

頁面包

考慮此內容結構:

content/
├── headless/    
│   ├── a.jpg
│   ├── b.jpg
│   ├── c.jpg
│   └── index.md  <-- front matter: headless = true
└── _index.md

主頁 模板中,使用 Site 對象上的 GetPage 方法來渲染無頭 頁面包 中的所有圖像:

layouts/home.html
{{ with .Site.GetPage "/headless" }}
  {{ range .Resources.ByType "image" }}
    <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
  {{ end }}
{{ end }}

Last updated: January 1, 0001
Improve this page