InSection
Page
物件上的 InSection
方法回報給定頁面是否位於指定的區段中。注意,當比較頁面與兄弟頁面時,此方法會回傳 true
。
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
當渲染 “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
區塊中,上下文(dot)是區段的 Page
物件,而不是傳入模板的 Page
物件。如果我們使用以下語法:
{{ with .Site.GetPage "/auctions" }}
{{ .InSection . }} → true
{{ end }}
渲染 “auction-1” 頁面時,結果將是錯誤的,因為我們是在比較區段頁面與自身。
{{ with .Site.GetPage "/auctions" }}
{{ $.InSection . }} → true
{{ end }}