Passing a "local variable" from template to another "ExecuteAsTemplate"

I have a template (a shortcode) that loads another template as a resource. I am using ExecuteAsTemplate to load the resource and use template processing on it.

In the first (shortcode) template, I have some “local variables”. Is there a way for me to see these in the executed template?

For example… here is a simple shortcode:

{{/* put run a script that is an asset */}}
{{- $div := "div1" -}}
{{- $text := "This is some text" -}}
{{- $script := resources.GetMatch "globalasset.js" -}}
{{- $exec := resources.ExecuteAsTemplate "foo.js" . $script -}}
<script src="{{ $exec.RelPermalink }}" type="module" defer></script>

and here is the template file it loads…

let div = document.getElementById("{{- $div -}}");
div.innerHTML += "From globalasset.js - {{ $name }} <br>";

what I’d like to have happen is that the $div in the 2nd template refers to the $div in the first. This is a violation of lexical scoping, so it isn’t surprising that I need to do something different.

A problem here is that I don’t fully understand the concept of the context.

Thank you!

The context can be your individual context (add a dict, add the page object, whatever). By adding the dot you are adding either the current page or whatever loop you are in (the context changes with with and range).

You can always use page itself to add the context of the current page (on list pages it’s the list page, not the page you might be ranging through). Or create your own dictionary:

{{ $context := dict "bla" "falsel" }}
{{- $exec := resources.ExecuteAsTemplate "foo.js" $context $script -}}

would result in foo.js having .bla set to “fasel”.
If you want to add the page context additionally:

{{ $context := dict "bla" "falsel" "page" . }}

Then .page would contain the page context, for instance .page.Title, etc.

Is that what you need?

1 Like

That is EXACTLY what I needed. Perfect. Awesome!

I had to do "page" .Page (rather than page .) - but it does what I intended!

Now I just need to figure out how to use this!

(it took me a minute to realize for every invocation of this, I need to generate a different name for the target object - but that’s a good thing, since it gives me control)