hugo/docs/content/extras/scratch.md

58 lines
2 KiB
Markdown
Raw Normal View History

2015-01-31 15:33:34 -05:00
---
aliases:
- /doc/scratch/
lastmod: 2015-08-02
2015-01-31 15:33:34 -05:00
date: 2015-01-22
menu:
main:
parent: extras
2015-02-09 10:52:52 -05:00
next: /extras/datafiles
2015-01-31 15:33:34 -05:00
prev: /extras/pagination
title: Scratch
weight: 80
---
`Scratch` -- a "scratchpad" for your node- or page-scoped variables. In most cases you can do well without `Scratch`, but there are some use cases that aren't solvable with Go's templates without `Scratch`'s help, due to scoping issues.
2015-08-02 01:00:43 -04:00
`Scratch` is added to both `Node` and `Page` -- with following methods:
* `Set` and `Add` takes a `key` and the `value` to add.
* `Get` returns the `value` for the `key` given.
* `SetInMap` takes a `key`, `mapKey` and `value`
* `GetSortedMapValues` returns array of values from `key` sorted by `mapKey`
2015-01-31 15:33:34 -05:00
2016-03-06 09:44:17 -05:00
`Set` and `SetInMap` can store values of any type.
For single values, `Add` accepts values that support Go's `+` operator. If the first `Add` for a key is an array or slice, the follwing adds will be appended to that list.
2015-01-31 15:33:34 -05:00
The scope of the backing data is global for the given `Node` or `Page`, and spans partial and shortcode includes.
## Sample usage
The usage is best illustrated with some samples:
```
{{ $.Scratch.Add "a1" 12 }}
{{ $.Scratch.Get "a1" }} {{/* => 12 */}}
{{ $.Scratch.Add "a1" 1 }}
{{ $.Scratch.Get "a1" }} // {{/* => 13 */}}
{{ $.Scratch.Add "a2" "AB" }}
{{ $.Scratch.Get "a2" }} {{/* => AB */}}
{{ $.Scratch.Add "a2" "CD" }}
{{ $.Scratch.Get "a2" }} {{/* => ABCD */}}
{{ $.Scratch.Set "v1" 123 }}
{{ $.Scratch.Get "v1" }} {{/* => 123 */}}
2015-08-02 01:00:43 -04:00
{{ $.Scratch.SetInMap "a3" "b" "XX" }}
{{ $.Scratch.SetInMap "a3" "a" "AA" }}
{{ $.Scratch.SetInMap "a3" "c" "CC" }}
{{ $.Scratch.SetInMap "a3" "b" "BB" }}
{{ $.Scratch.GetSortedMapValues "a3" }} {{/* => []interface {}{"AA", "BB", "CC"} */}}
2015-01-31 15:33:34 -05:00
```
**Note:** The examples above uses the special `$` variable, which refers to the top-level node. This is the behavior you most likely want, and will help remove some confusion when using `Scratch` inside page range loops -- and you start inadvertently calling the wrong `Scratch`. But there may be use cases for `{{ .Scratch.Add "key" "some value" }}`.
2015-01-31 15:33:34 -05:00