Debian Codegraph @

docs/content/en/methods/page/InSection.md

raw
1 ---
2 title: InSection
3 description: Reports whether the given page is in the given section.
4 categories: []
5 keywords: []
6 params:
7 functions_and_methods:
8 returnType: bool
9 signatures: [PAGE.InSection SECTION]
10 ---
11
12 {{% glossary-term section %}}
13
14 The `InSection` method on a `Page` object reports whether the given page is in the given section. Note that the method returns `true` when comparing a page to a sibling.
15
16 With this content structure:
17
18 ```tree
19 content/
20 ├── auctions/
21 │ ├── 2023-11/
22 │ │ ├── _index.md
23 │ │ ├── auction-1.md
24 │ │ └── auction-2.md
25 │ ├── 2023-12/
26 │ │ ├── _index.md
27 │ │ ├── auction-3.md
28 │ │ └── auction-4.md
29 │ ├── _index.md
30 │ ├── bidding.md
31 │ └── payment.md
32 └── _index.md
33 ```
34
35 When rendering the `auction-1` page:
36
37 ```go-html-template
38 {{ with .Site.GetPage "/" }}
39 {{ $.InSection . }} → false
40 {{ end }}
41
42 {{ with .Site.GetPage "/auctions" }}
43 {{ $.InSection . }} → false
44 {{ end }}
45
46 {{ with .Site.GetPage "/auctions/2023-11" }}
47 {{ $.InSection . }} → true
48 {{ end }}
49
50 {{ with .Site.GetPage "/auctions/2023-11/auction-2" }}
51 {{ $.InSection . }} → true
52 {{ end }}
53 ```
54
55 In the examples above we are coding defensively using the [`with`][] statement, returning nothing if the page does not exist. By adding an [`else`][] clause we can do some error reporting:
56
57 ```go-html-template
58 {{ $path := "/auctions/2023-11" }}
59 {{ with .Site.GetPage $path }}
60 {{ $.InSection . }} → true
61 {{ else }}
62 {{ errorf "Unable to find the section with path %s" $path }}
63 {{ end }}
64 ```
65
66 ## Understanding context
67
68 Inside of the `with` block, the [context](g) (the dot) is the section `Page` object, not the `Page` object passed into the template. If we were to use this syntax:
69
70 ```go-html-template
71 {{ with .Site.GetPage "/auctions" }}
72 {{ .InSection . }} → true
73 {{ end }}
74 ```
75
76 The result would be wrong when rendering the `auction-1` page because we are comparing the section page to itself.
77
78 > [!NOTE]
79 > Use the `$` to get the context passed into the template.
80
81 ```go-html-template
82 {{ with .Site.GetPage "/auctions" }}
83 {{ $.InSection . }} → true
84 {{ end }}
85 ```
86
87 > [!NOTE]
88 > Gaining a thorough understanding of context is critical for anyone writing template code.
89
90 [`else`]: /functions/go-template/else/
91 [`with`]: /functions/go-template/with/