| 1 |
--- |
| 2 |
title: Ordinal |
| 3 |
description: Returns the zero-based ordinal of the shortcode in relation to its parent. |
| 4 |
categories: [] |
| 5 |
keywords: [] |
| 6 |
params: |
| 7 |
functions_and_methods: |
| 8 |
returnType: int |
| 9 |
signatures: [SHORTCODE.Ordinal] |
| 10 |
--- |
| 11 |
|
| 12 |
The `Ordinal` method returns the zero-based ordinal of the shortcode in relation to its parent. If the parent is the page itself, the ordinal represents the position of this shortcode in the page content. |
| 13 |
|
| 14 |
> [!NOTE] |
| 15 |
> Hugo increments the ordinal with each shortcode call, regardless of the specific shortcode type. This means that the ordinal value is tracked sequentially across all shortcodes within a given page. |
| 16 |
|
| 17 |
This method is useful for, among other things, assigning unique element IDs when a shortcode is called two or more times from the same page. For example: |
| 18 |
|
| 19 |
```md {file="content/about.md"} |
| 20 |
{{</* img src="images/a.jpg" */>}} |
| 21 |
|
| 22 |
{{</* img src="images/b.jpg" */>}} |
| 23 |
``` |
| 24 |
|
| 25 |
This shortcode performs error checking, then renders an HTML `img` element with a unique `id` attribute: |
| 26 |
|
| 27 |
```go-html-template {file="layouts/_shortcodes/img.html"} |
| 28 |
{{ $src := "" }} |
| 29 |
{{ with .Get "src" }} |
| 30 |
{{ $src = . }} |
| 31 |
{{ with resources.Get $src }} |
| 32 |
{{ $id := printf "img-%03d" $.Ordinal }} |
| 33 |
<img id="{{ $id }}" src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt=""> |
| 34 |
{{ else }} |
| 35 |
{{ errorf "The %q shortcode was unable to find %s. See %s" $.Name $src $.Position }} |
| 36 |
{{ end }} |
| 37 |
{{ else }} |
| 38 |
{{ errorf "The %q shortcode requires a 'src' argument. See %s" .Name .Position }} |
| 39 |
{{ end }} |
| 40 |
``` |
| 41 |
|
| 42 |
Hugo renders the page to: |
| 43 |
|
| 44 |
```html |
| 45 |
<img id="img-000" src="/images/a.jpg" width="600" height="400" alt=""> |
| 46 |
<img id="img-001" src="/images/b.jpg" width="600" height="400" alt=""> |
| 47 |
``` |
| 48 |
|
| 49 |
> [!NOTE] |
| 50 |
> In the _shortcode_ template above, the [`with`][] statement is used to create conditional blocks. Remember that the `with` statement binds context (the dot) to its expression. Inside of a `with` block, preface shortcode method calls with a `$` to access the top-level context passed into the template. |
| 51 |
|
| 52 |
[`with`]: /functions/go-template/with/ |