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