HUGO

How to get scratch.get value from partial, with dict value set

I want to get the .Scratch.Get value outside the partial when I set the .Scratch.Set value in the partial.

It works when I don’t set any dict value with the partial. but if I set any value with dict, it doesn’t work anymore.

Working Code:

partial/hello.html

{{ $foo:= "Hello World" }}
{{ $.Scratch.Set "foo" $foo }}

index.html

{{ partial "foo.html" .  }}
{{ $.Scratch.Get "foo" }}

NOT Working Code:

partial/hello.html

{{ $foo:= .Foo }}
{{ $.Scratch.Set "foo" $foo }}

index.html

{{ partial "foo.html" (dict "Foo" "Hello World") }}
{{ $.Scratch.Get "foo" }}

it doesn’t return the value.

.Scratch is .Page method:

Here, you didnt pass .Page / . to the partial

{{ partial "foo.html" (dict "Foo" "Hello World") }}

If you want to use .Page.Scratch, you need to pass it to the partial:

partial/hello.html

{{ $foo:= .Foo }}
{{ .Page.Scratch.Set "foo" $foo }}

index.html

{{ partial "foo.html" (dict "Page" . "Foo" "Hello World") }}
{{ .Scratch.Get "foo" }}

Extra tip, if you want to avoid polluting the .Page.Scratch you can always use Local Scratch using newScratch function:

partial/hello.html

{{ $foo:= .Foo }}
{{ .my_scratch.Set "foo" $foo }}

index.html

{{ $my_scratch := newScratch }}
{{ partial "foo.html" (dict "my_scratch" $my_scratch "Foo" "Hello World") }}
{{ $my_scratch.Get "foo" }}
1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.