Scratch not working inside define in a partial

Hugo v0.30

I assume it should be possible to use Scratch within a define as demonstrated in the section Attempt 2 with Scratch - yikes! here, but I cannot get Scratch to work inside a define in a partial. In layouts/partials/header.html I have the following:

{{ $.Scratch.Set "a" "A" }}
<p>a: {{ $.Scratch.Get "a" }}</p>

{{ template "foo" }}
    
{{ define "foo" }}
    {{ $.Scratch.Set "b" "B" }}
    <p>b: {{ $.Scratch.Get "b" }}</p>
{{ end }}

, this result in the following output:

a: A

b:

I expected the following output:

a: A

b: B

How can I use Scratch inside the foo block/template?

What is the {{ define "foo" }} ... {{ end }} construct called in Hugo-lingo when used to introduce a new block/template within a partial, i.e., "foo" has not been introduced as block in any of the layouts/_default base templates? It is referred to as a template, block or something else?

You need to pass on the context, so:

{{ template “foo” . }}

Should work, I believe.

Thanks @bep, adding the context . when calling the foo template solved my problem.

This example exposed my misunderstanding of the global context $. My new understanding is, that when passing the context . to the foo template, the global context $ is part of the context passed to template foo. Is this the right way to look at this?

$. Is the outer-most context in the current template. Nothing global about it.

Said another way, $ is the initial template context. Don’t think global. Think initial.

Not sure why it needed to be said another way :slight_smile: “initial” indicates it changes/gets overwritten. It doesn’t. It is the entry-level or outer-most context.

Right. Initial. :smile: