IsAncestor
语法
PAGE1.IsAncestor PAGE2
返回
bool
一个 *章节* 是一个顶级内容目录,或任何包含 _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 "/" }}
{{ $.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 }}