Possible to count shortcodes in layout template?

I asked the same question and forgot .Ordinal already: There is a variable called .Ordinal in each shortcode that seems to increments on subsequent calls.

I would, however, do it like this with scratch (untested, might contain typoes):

{{ with .Page.Scratch.Get "counter" }}
  {{ .Page.Scratch.Set "counter" (add . 1) }}
{{ else }}
  {{/* first call, so counter is 1 */}}
  {{ .Page.Scratch.Set "counter" 1 }}
{{ end }}
{{ $counter := .Page.Scratch.Get "counter"}}

Note that .Scratch inside the shortcode stays inside the shortcode. You need to call .Page.Scratch to catch the “global” scratch variable.

I am not sure if that with part will throw any error if the variable does not exist (first call). It shouldn’t…

1 Like