IsDescendant
Syntax
PAGE1.IsDescendant PAGE2
Returns
bool
一个 section 是最高级别的内容目录,或者是带有索引文件 index.md 的任意内容目录。
内容结构如下:
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 "/" }}
  {{ $.IsDescendant . }} → true
{{ end }}
{{ with .Site.GetPage "/auctions" }}
  {{ $.IsDescendant . }} → false
{{ end }}
{{ with .Site.GetPage "/auctions/2023-11" }}
  {{ $.IsDescendant . }} → false
{{ end }}
{{ with .Site.GetPage "/auctions/2023-11/auction-2" }}
  {{ $.IsDescendant . }} → false
{{ end }}
上面的示例中,我们使用了with语句进行防御性编码,如果页面不存在就返回空值。通过添加else子句,我们可以进行一些错误报告:
{{ $path := "/auctions/2023-11" }}
{{ with .Site.GetPage $path }}
  {{ $.IsDescendant . }} → true
{{ else }}
  {{ errorf "无法找到路径为 %s 的页面" $path }}
{{ end }}
理解上下文
在with块中,上下文(即点)是部分Page对象,而不是传递给模板的Page对象。如果我们使用以下语法:
{{ with .Site.GetPage "/auctions" }}
  {{ .IsDescendant . }} → true
{{ end }}
当渲染“auction-1”页面时,结果会不正确,因为我们将部分页面与其自身进行比较。
{{ with .Site.GetPage "/auctions" }}
  {{ $.IsDescendant . }} → true
{{ end }}