Study Guide: Using Scratch to increment a counter in a range
Scratch was originally added to Hugo to get around a limitation of Go templates. Due to advances in Go Templates, Scratch is no longer needed in most situations, but it still works.
{{/* Create a scratch variable called "counter", and set it to zero. */}}
{{- $.Scratch.Set "counter" 0 }}
{{/* Range through all site pages. */}}
{{ range .Pages }}
{{/* Increment the counter by 1. */}}
{{- $.Scratch.Set "counter" (add ($.Scratch.Get "counter") 1) }}
{{/* Display a numbered list of pages. */}}
<div>Count: {{$.Scratch.Get "counter" }} {{ , }}</div>
{{/* End the range. */}}
{{- end }}
Scratch is no longer needed very often. The below method avoids using scratch
by creating new slice
variables $index
and $element
slices from to “range” through the data.
{{/* Range through all site pages. */}}
{{ range $index, $element := .Pages }}
{{/* Because $index is zero-based, add 1 for more reasonable display to humans. */}}
{{ add $index 1 }}
{{/* Display a numbered list of pages. */}}
<div>Count: {{ $index }} - {{ $element }}</div>
{{/* End the range. */}}
{{ end }}
More Information
- https://gohugo.io/functions/scratch/
- https://discourse.gohugo.io/t/how-counting-up-a-variable-in-range/586/7
Source: https://class.ronliskey.com/study/computing/hugo-using-scratch-for-counter-in-range/