Hi
I am (like many before and many to follow) confused about scoping of Scratch and variables in general.
What I’m trying to do is make a shortcode test behave differently if it is called inside another shortcode testwrap, by setting a Scratch flag, but I can’t get it to work. I did some experiments to try and figure out what is going on:
###/layouts/shortcodes/testwrap.html:
{{ .Scratch.Add "flag" "A" }}
{{ $.Scratch.Add "flag" "a" }}
{{ .Page.Scratch.Add "flag" "B" }}
{{ $.Page.Scratch.Add "flag" "b" }}
<p>testwrap .Scratch.Get "flag" = {{ .Scratch.Get "flag" }}</p>
<p>testwrap $.Scratch.Get "flag" = {{ $.Scratch.Get "flag" }}</p>
<p>testwrap .Page.Scratch.Get "flag" = {{ .Page.Scratch.Get "flag" }}</p>
<p>testwrap $.Page.Scratch.Get "flag" = {{ $.Page.Scratch.Get "flag" }}</p>
{{ .Inner }}
<!-- clear flags here if they are only supposed to be visible within .Inner -->
###/layouts/shortcodes/test.html:
{{ .Scratch.Add "flag" "C" }}
{{ $.Scratch.Add "flag" "c" }}
{{ .Page.Scratch.Add "flag" "D" }}
{{ $.Page.Scratch.Add "flag" "d" }}
<p>test .Scratch.Get "flag" = {{ .Scratch.Get "flag" }}</p>
<p>test $.Scratch.Get "flag" = {{ $.Scratch.Get "flag" }}</p>
<p>test .Page.Scratch.Get "flag" = {{ .Page.Scratch.Get "flag" }}</p>
<p>test $.Page.Scratch.Get "flag" = {{ $.Page.Scratch.Get "flag" }}</p>
###/content/test.md:
testwrap:
{{< testwrap >}}
test inside testwrap:
{{< test >}}
{{< /testwrap >}}
test outside testwrap:
{{< test >}}
###Result:
testwrap:
testwrap .Scratch.Get "flag" = Aa
testwrap $.Scratch.Get "flag" = Aa
testwrap .Page.Scratch.Get "flag" = DdBb
testwrap $.Page.Scratch.Get "flag" = DdBb
test inside testwrap:
test .Scratch.Get "flag" = Cc
test $.Scratch.Get "flag" = Cc
test .Page.Scratch.Get "flag" = Dd
test $.Page.Scratch.Get "flag" = Dd
test outside testwrap:
test .Scratch.Get "flag" = Cc
test $.Scratch.Get "flag" = Cc
test .Page.Scratch.Get "flag" = DdBbDd
test $.Page.Scratch.Get "flag" = DdBbDd
So as far as I can tell:
-
.Scratch=$.Scratchand.Page.Scratch=$.Page.Scratch(I put the.Scratch.Addstatements inside anifblock - it made no difference) -
$.Scratchis the shortcode-scoped Scratch -
$.Page.Scratchis shared between shortcodes called from the same scope (e.g. betweentestwrapand the “outside”test) - can use this to pass flags between shortcodes called from the same scope - You can pass flags from an inner shortcode to an outer shortcode (e.g. from the “inner”
testtotestwrap) but the behaviour is very strange:- The “inner”
testis parsed in its entirety before any oftestwrapis parsed (I would have expected$.Page.Scratch.Get "flag" = Bbbefore{{.Inner}}is called and$.Page.Scratch.Get "flag" = BbDdafter{{.Inner}}is called.) - Within the inner
test,$.Page.Scratch.Getappears to point to the local Scratch only, but$.Page.Scratch.Addappears to point to the local Scratch AND the page-scoped Scratch.
- The “inner”
- It doesn’t seem to be possible to pass a flag from
testwraptotest
Is all of this the correct behaviour?