Study Guides | | Using Scratch to increment a counter in a range

Study Guide: Using Scratch to increment a counter in a range

{{/* 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

Source: https://class.ronliskey.com/study/computing/hugo-using-scratch-for-counter-in-range/