IsAncestor
報告 PAGE1 是否是 PAGE2 的祖先。
Syntax
PAGE1.IsAncestor PAGE2
Returns
bool
使用此內容結構:
content/
├── auctions/
│ ├── 2023-11/
│ │ ├── _index.md
│ │ ├── auction-1.md
│ │ └── auction-2.md
│ ├── 2023-12/
│ │ ├── _index.md
│ │ ├── auction-3.md
│ │ └── auction-4.md
│ ├── _index.md
│ ├── bidding.md
│ └── payment.md
└── _index.md渲染 “auctions” 頁面時:
{{ with .Site.GetPage "/" }}
{{ $.IsAncestor . }} → false
{{ end }}
{{ with .Site.GetPage "/auctions" }}
{{ $.IsAncestor . }} → false
{{ end }}
{{ with .Site.GetPage "/auctions/2023-11" }}
{{ $.IsAncestor . }} → true
{{ end }}
{{ with .Site.GetPage "/auctions/2023-11/auction-2" }}
{{ $.IsAncestor . }} → true
{{ end }}在上面的示例中,我們使用 with 語句防御性編碼,如果頁面不存在則不返回任何內容。通過添加 else 子句,我們可以進行錯誤報告:
{{ $path := "/auctions/2023-11" }}
{{ with .Site.GetPage $path }}
{{ $.IsAncestor . }} → true
{{ else }}
{{ errorf "Unable to find the section with path %s" $path }}
{{ end }}理解上下文
在 with 塊內,上下文(點)是欄目 Page 對象,而不是傳遞給模板的 Page 對象。如果我們使用此語法:
{{ with .Site.GetPage "/auctions" }}
{{ .IsAncestor . }} → true
{{ end }}渲染 “auction-1” 頁面時結果將不正確,因為我們將欄目頁面與其自身進行比較。
使用 $ 獲取傳遞給模板的上下文。
{{ with .Site.GetPage "/auctions" }}
{{ $.IsAncestor . }} → true
{{ end }}對於編寫模板代碼的人來說,徹底理解上下文至關重要。