InSection
语法
PAGE.InSection SECTION
返回
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 "Unable to find the section with path %s" $path }}
{{ end }}
理解上下文
在 with
块内部,上下文(点)是章节 Page
对象,而不是传递到模板的 Page
对象。如果我们使用此语法
{{ with .Site.GetPage "/auctions" }}
{{ .InSection . }} → true
{{ end }}
在渲染“auction-1”页面时,结果将是错误的,因为我们将章节页面与其自身进行比较。
{{ with .Site.GetPage "/auctions" }}
{{ $.InSection . }} → true
{{ end }}