InSection
Syntax
PAGE.InSection SECTION
Returns
bool
Page 对象上的 InSection 方法报告给定页面是否在给定部分中。请注意,当将页面与同级页面进行比较时,该方法返回 true 。
一个 章节 是一个顶级内容目录,或者任何包含 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
渲染 “auction-1” 页面时:
{{ with .Site.GetPage "/" }}
  {{ $.InSection . }} → false
{{ end }}
{{ with .Site.GetPage "/auctions" }}
  {{ $.InSection . }} → false
{{ end }}
{{ with .Site.GetPage "/auctions/2023-11" }}
  {{ $.InSection . }} → true
{{ end }}
{{ with .Site.GetPage "/auctions/2023-11/auction-2" }}
  {{ $.InSection . }} → true
{{ end }}
在上面的示例中,我们使用 with 语句进行防御性编码,如果页面不存在则不返回任何内容。通过添加 else 子句,我们可以进行一些错误报告:
{{ $path := "/auctions/2023-11" }}
{{ with .Site.GetPage $path }}
  {{ $.InSection . }} → true
{{ else }}
  {{ errorf "无法找到路径为 %s 的部分" $path }}
{{ end }}
理解上下文
在 with 块内, 上下文 (点)是部分 Page 对象,而不是传递到模板中的 Page 对象。如果我们使用此语法:
{{ with .Site.GetPage "/auctions" }}
  {{ .InSection . }} → true
{{ end }}
当渲染 “auction-1” 页面时,结果将是错误的,因为我们正在将部分页面与其自身进行比较。
{{ with .Site.GetPage "/auctions" }}
  {{ $.InSection . }} → true
{{ end }}