Debian Codegraph @

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

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