Store
- Syntax
- SHORTCODE.Store
- Returns
- maps.Scratch
Usage
The Store method on a Shortcode object returns a persistent data structure for storing and manipulating keyed values, scoped to the current shortcode. Use a different function or method to create a data structure with a different scope.
With the introduction of the collections.NewScratch function, and the ability to assign values to template variables after initialization, the Store method within a shortcode is mostly obsolete.
Methods
Use these methods on the data structure:
Set- Sets the value of the given key.
Get- (
any) Returns the value of the given key. Add- Adds the given value to the existing value of the given key. If the existing value is a slice,
Addappends the given value to the slice. Otherwise,Addcombines the values with Go’s+operator, such as adding two numbers or joining two strings. If the key does not exist,Addsets the value of the key. SetInMap- Takes a key, a map key, and a value, and sets the value of the map key within the map stored under the given key.
DeleteInMap- Takes a key and a map key, and removes the map key from the map stored under the given key.
GetSortedMapValues- (
[]any) Returns the values of the map stored under the given key, sorted by map key. Delete- Removes the given key.
Scope
The method or function used to create the data structure determines its scope. For example, use the Store method on a Page object to create a data structure scoped to the page.
| Scope | Method or function |
|---|---|
| page | PAGE.Store |
| site | SITE.Store |
| global | hugo.Store |
| local | collections.NewScratch |
| shortcode | SHORTCODE.Store |
Examples
{{ .Store.Set "greeting" "Hello" }}
{{ .Store.Get "greeting" }} → HelloAdding a string to a string:
{{ .Store.Set "greeting" "Hello" }}
{{ .Store.Add "greeting" "Welcome" }}
{{ .Store.Get "greeting" }} → HelloWelcomeAdding a number to a number:
{{ .Store.Set "total" 3 }}
{{ .Store.Add "total" 7 }}
{{ .Store.Get "total" }} → 10Appending to a slice:
{{ .Store.Set "greetings" (slice "Hello") }}
{{ .Store.Add "greetings" (slice "Welcome" "Cheers") }}
{{ .Store.Get "greetings" }} → [Hello Welcome Cheers]Setting values in a map:
{{ .Store.SetInMap "greetings" "english" "Hello" }}
{{ .Store.SetInMap "greetings" "french" "Bonjour" }}
{{ .Store.Get "greetings" }} → map[english:Hello french:Bonjour]Deleting a value from a map:
{{ .Store.SetInMap "greetings" "english" "Hello" }}
{{ .Store.SetInMap "greetings" "french" "Bonjour" }}
{{ .Store.DeleteInMap "greetings" "english" }}
{{ .Store.Get "greetings" }} → map[french:Bonjour]Getting the map values sorted by map key:
{{ .Store.SetInMap "greetings" "english" "Hello" }}
{{ .Store.SetInMap "greetings" "french" "Bonjour" }}
{{ .Store.GetSortedMapValues "greetings" }} → [Hello Bonjour]Deleting a key:
{{ .Store.Set "greeting" "Hello" }}
{{ .Store.Delete "greeting" }}