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 ## Basic usage
17
18 With this content structure:
19
20 ```tree
21 content/
22 ├── auctions/
23 │ ├── 2023-11/
24 │ │ ├── _index.md
25 │ │ ├── auction-1.md
26 │ │ └── auction-2.md
27 │ ├── 2023-12/
28 │ │ ├── _index.md
29 │ │ ├── auction-3.md
30 │ │ └── auction-4.md
31 │ ├── _index.md
32 │ ├── bidding.md
33 │ └── payment.md
34 └── _index.md
35 ```
36
37 When rendering the `auction-1` page:
38
39 ```go-html-template
40 {{ with .Site.GetPage "/" }}
41 {{ $.InSection . }} → false
42 {{ end }}
43
44 {{ with .Site.GetPage "/auctions" }}
45 {{ $.InSection . }} → false
46 {{ end }}
47
48 {{ with .Site.GetPage "/auctions/2023-11" }}
49 {{ $.InSection . }} → true
50 {{ end }}
51
52 {{ with .Site.GetPage "/auctions/2023-11/auction-2" }}
53 {{ $.InSection . }} → true
54 {{ end }}
55 ```
56
57 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:
58
59 ```go-html-template
60 {{ $path := "/auctions/2023-11" }}
61 {{ with .Site.GetPage $path }}
62 {{ $.InSection . }} → true
63 {{ else }}
64 {{ errorf "Unable to find the section with path %s" $path }}
65 {{ end }}
66 ```
67
68 ## Understanding context
69
70 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:
71
72 ```go-html-template
73 {{ with .Site.GetPage "/auctions" }}
74 {{ .InSection . }} → true
75 {{ end }}
76 ```
77
78 The result would be wrong when rendering the `auction-1` page because we are comparing the section page to itself.
79
80 > [!NOTE]
81 > Use the `$` to get the context passed into the template.
82
83 ```go-html-template
84 {{ with .Site.GetPage "/auctions" }}
85 {{ $.InSection . }} → true
86 {{ end }}
87 ```
88
89 > [!NOTE]
90 > Gaining a thorough understanding of context is critical for anyone writing template code.
91
92 [`else`]: /functions/go-template/else/
93 [`with`]: /functions/go-template/with/