HUGO
Menu
GitHub 87548 stars Mastodon

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 }}

对于编写模板代码的人来说,彻底理解上下文至关重要。


Last updated: January 1, 0001
Improve this page