Can I identify the first instance of a child somehow?

I’m going through the painful task of implementing Bootstrap tabs. I’m creating a shortcode with the following structure:

{{% tabs %}}
    {{% tab "Tab name" %}}
    {{% /tab %}}
    {{% tab "Different name" %}}
    {{% /tab %}}
{{% /tabs %}}

I need to apply a default attribute to the first tab automatically. However, I don’t want to have to add a parameter (like “first”) to the child shortcode, because this will occur in every page the same way and feels totally redundant.

Any ideas?

I thought of defining a counter variable on the parent, setting it to 0, requesting it on the child and immediately setting it to 1. That doesn’t work. I’m using .Page.Scratch.Set on the parent but when I use .Parent.Scratch.Get on the child it always returns <nil>.

From Hugo 0.40 you have a .Ordinal available on the shortcode. It starts at 0 (from either the page or the parent shortcode).

The shortcodes are rendered inner-out, so there are restrictions on what you can do with .Scratch, but you can get creative if you really want to:


Not sure if I want to post the above as an example of “best practice”, but I had to port a tab plugin from Jekyll to Hugo, and the above was the solution I came up with.

2 Likes

Oh wow thanks @bep, took me a minute there but I see what you did… you’re basically using the child just to get content and parameters and pass it to the parent, and the parent does all the loops and outputting at once. This is definitely what I was looking for…
As for .Ordinal is that anywhere on the documentation? How can that be used?

many thanks

I added a line in the docs about Ordinal now: https://gohugo.io/variables/shortcodes/#readout

{ { .Ordinal }} …

1 Like

Wow, impressive thanks :slight_smile: