HUGO

  • News
  • Docs
  • Themes
  • Showcase
  • Community
  • GitHub
gohugoio Star
FUNCTIONS

.Scratch

Acts as a “scratchpad” to store and manipulate data.

Scratch is a Hugo feature designed to conveniently manipulate data in a Go Template world. It is either a Page or Shortcode method for which the resulting data will be attached to the given context, or it can live as a unique instance stored in a variable.

Note that Scratch was initially created as a workaround for a Go template scoping limitation that affected Hugo versions prior to 0.48. For a detailed analysis of .Scratch and contextual use cases, see this blog post.

Contexted .Scratch vs. local newScratch

Since Hugo 0.43, there are two different ways of using Scratch:

The Page’s .Scratch

.Scratch is available as a Page method or a Shortcode method and attaches the “scratched” data to the given page. Either a Page or a Shortcode context is required to use .Scratch.

{{ .Scratch.Set "greeting" "bonjour" }}
{{ range .Pages }}
  {{ .Scratch.Set "greeting" (print "bonjour" .Title) }}
{{ end }}

The local newScratch

A Scratch instance can also be assigned to any variable using the newScratch function. In this case, no Page or Shortcode context is required and the scope of the scratch is only local. The methods detailed below are available from the variable the Scratch instance was assigned to.

{{ $data := newScratch }}
{{ $data.Set "greeting" "hola" }}

Methods

A Scratch has the following methods:

Note that the following examples assume a local Scratch instance has been stored in $scratch.

.Set

Set the value of a given key.

{{ $scratch.Set "greeting" "Hello" }}

.Get

Get the value of a given key.

{{ $scratch.Set "greeting" "Hello" }}
----
{{ $scratch.Get "greeting" }} > Hello

.Add

Add a given value to existing value(s) of the given key.

For single values, Add accepts values that support Go’s + operator. If the first Add for a key is an array or slice, the following adds will be appended to that list.

{{ $scratch.Add "greetings" "Hello" }}
{{ $scratch.Add "greetings" "Welcome" }}
----
{{ $scratch.Get "greetings" }} > HelloWelcome
{{ $scratch.Add "total" 3 }}
{{ $scratch.Add "total" 7 }}
----
{{ $scratch.Get "total" }} > 10
{{ $scratch.Add "greetings" (slice "Hello") }}
{{ $scratch.Add "greetings" (slice "Welcome" "Cheers") }}
----
{{ $scratch.Get "greetings" }} > []interface {}{"Hello", "Welcome", "Cheers"}

.SetInMap

Takes a key, mapKey and value and adds a map of mapKey and value to the given key.

{{ $scratch.SetInMap "greetings" "english" "Hello" }}
{{ $scratch.SetInMap "greetings" "french" "Bonjour" }}
----
{{ $scratch.Get "greetings" }} > map[french:Bonjour english:Hello]

.DeleteInMap

Takes a key and mapKey and removes the map of mapKey from the given key.

{{ .Scratch.SetInMap "greetings" "english" "Hello" }}
{{ .Scratch.SetInMap "greetings" "french" "Bonjour" }}
----
{{ .Scratch.DeleteInMap "greetings" "english" }}
----
{{ .Scratch.Get "greetings" }} > map[french:Bonjour]

.GetSortedMapValues

Return an array of values from key sorted by mapKey.

{{ $scratch.SetInMap "greetings" "english" "Hello" }}
{{ $scratch.SetInMap "greetings" "french" "Bonjour" }}
----
{{ $scratch.GetSortedMapValues "greetings" }} > [Hello Bonjour]

.Delete

Remove the given key.

{{ $scratch.Set "greeting" "Hello" }}
----
{{ $scratch.Delete "greeting" }}

.Values

Return the raw backing map. Note that you should only use this method on the locally scoped Scratch instances you obtain via newScratch, not .Page.Scratch etc., as that will lead to concurrency issues.

Related functions

  • .Store
  • About Hugo
    • Overview
    • What is Hugo
    • Hugo features
    • Static site generators
    • Hugo's security model
    • Hugo and the GDPR
    • License
  • Installation
    • Overview
    • macOS
    • Linux
    • Windows
    • BSD
  • Getting started
    • Overview
    • Quick start
    • Basic usage
    • Directory structure
    • Configuration
    • Configure markup
    • Glossary of terms
    • External learning resources
  • Hugo Modules
    • Overview
    • Configure Hugo modules
    • Use Hugo Modules
    • Theme components
  • Content management
    • Overview
    • Organization
    • Page bundles
    • Content formats
    • Diagrams
    • Front matter
    • Build options
    • Page resources
    • Image processing
    • Shortcodes
    • Related content
    • Sections
    • Content types
    • Archetypes
    • Taxonomies
    • Summaries
    • Links and cross references
    • URL management
    • Menus
    • Static files
    • Table of contents
    • Comments
    • Multilingual
    • Syntax highlighting
  • Templates
    • Overview
    • Templating
    • Template lookup order
    • Base templates and blocks
    • Single page templates
    • List templates
    • Homepage template
    • Section templates
    • Taxonomy templates
    • Pagination
    • Content view templates
    • Partial templates
    • Shortcode templates
    • Menu templates
    • Data templates
    • RSS templates
    • Sitemap templates
    • Local file templates
    • Internal templates
    • Render hooks
    • Custom output formats
    • 404 page
    • Robots.txt
    • Template debugging
  • Functions
    • Overview
    • .AddDate
    • .Format
    • .Get
    • .GetPage
    • .HasMenuCurrent
    • .IsMenuCurrent
    • .Param
    • .Render
    • .RenderString
    • .Scratch
    • .Store
    • .Unix
    • absLangURL
    • absURL
    • after
    • anchorize
    • append
    • apply
    • base64Decode
    • base64Encode
    • chomp
    • collections.Reverse
    • complement
    • cond
    • countrunes
    • countwords
    • crypto.FNV32a
    • debug.Dump
    • default
    • delimit
    • dict
    • duration
    • echoParam
    • emojify
    • eq
    • errorf
    • erroridf
    • fileExists
    • findRE
    • findRESubmatch
    • first
    • float
    • ge
    • getCSV
    • getenv
    • getJSON
    • group
    • gt
    • highlight
    • hmac
    • htmlEscape
    • htmlUnescape
    • hugo
    • humanize
    • i18n
    • Image filters
    • in
    • index
    • int
    • intersect
    • isset
    • jsonify
    • keyVals
    • lang.FormatAccounting
    • lang.FormatCurrency
    • lang.FormatNumber
    • lang.FormatNumberCustom
    • lang.FormatPercent
    • lang.Merge
    • last
    • le
    • len
    • lower
    • lt
    • markdownify
    • math
    • md5
    • merge
    • ne
    • newScratch
    • now
    • os.Stat
    • page
    • partial
    • partialCached
    • path.Base
    • path.BaseName
    • path.Clean
    • path.Dir
    • path.Ext
    • path.Join
    • path.Split
    • plainify
    • pluralize
    • print
    • printf
    • println
    • querify
    • range
    • readDir
    • readFile
    • ref
    • reflect.IsMap
    • reflect.IsSlice
    • relLangURL
    • relref
    • relURL
    • replace
    • replaceRE
    • safeCSS
    • safeHTML
    • safeHTMLAttr
    • safeJS
    • safeJSStr
    • safeURL
    • seq
    • sha1
    • sha256
    • shuffle
    • singularize
    • site
    • slice
    • slicestr
    • sort
    • split
    • string
    • strings.Contains
    • strings.ContainsAny
    • strings.ContainsNonSpace
    • strings.Count
    • strings.FirstUpper
    • strings.HasPrefix
    • strings.HasSuffix
    • strings.Repeat
    • strings.RuneCount
    • strings.TrimLeft
    • strings.TrimPrefix
    • strings.TrimRight
    • strings.TrimSuffix
    • substr
    • symdiff
    • templates.Exists
    • time
    • time.Format
    • time.ParseDuration
    • title
    • transform.CanHighlight
    • transform.HighlightCodeBlock
    • transform.Remarshal
    • transform.Unmarshal
    • trim
    • truncate
    • union
    • uniq
    • upper
    • urlize
    • urlquery
    • urls.JoinPath
    • urls.Parse
    • warnf
    • where
    • with
  • Variables
    • Overview
    • Site variables
    • Page variables
    • Shortcode variables
    • Pages methods
    • Taxonomy variables
    • File variables
    • Menu variables
    • Git variables
    • Sitemap variables
  • Hugo Pipes
    • Overview
    • Introduction
    • Transpile Sass to CSS
    • PostCSS
    • PostProcess
    • JavaScript building
    • Babel
    • Asset minification
    • Concatenating assets
    • Fingerprinting and SRI hashing
    • Resource from string
    • Resource from template
  • CLI
  • Troubleshooting
    • Overview
    • Frequently asked questions
    • Build performance
  • Developer tools
    • Overview
    • Editor plugins
    • Frontends
    • Search
    • Migrations
    • Other projects
  • Hosting and deployment
    • Overview
    • Hugo Deploy
    • Deploy with Rclone
    • Deploy with Rsync
    • Host on 21YunBox
    • Host on AWS Amplify
    • Host on Azure Static Web Apps
    • Host on Cloudflare Pages
    • Host on Firebase
    • Host on GitHub Pages
    • Host on GitLab Pages
    • Host on KeyCDN
    • Host on Netlify
    • Host on Render
  • Contribute
    • Overview
    • Development
    • Documentation
    • Themes
  • Maintenance
Last updated: September 30, 2023: Add return type to functions (a3a40ff9)
Improve this page
By the Hugo Authors
Hugo Logo
  • File an Issue
  • Get Help
  • @GoHugoIO
  • @spf13
  • @bepsays

Netlify badge

 

Hugo Sponsors

 

The Hugo logos are copyright © Steve Francia 2013–2023.

The Hugo Gopher is based on an original work by Renée French.

  • News
  • Docs
  • Themes
  • Showcase
  • Community
  • GitHub
  • About Hugo
  • Installation
  • Getting started
  • Hugo Modules
  • Content management
  • Templates
  • Functions
  • Variables
  • Hugo Pipes
  • CLI
  • Troubleshooting
  • Developer tools
  • Hosting and deployment
  • Contribute
  • Maintenance