Question about variable overwrites in Hugo 0.48

As per the new release announcement the following works great:

{{ $var := "Hugo Page" }}
{{ if .IsHome }}
	{{ $var = "Hugo Home" }}
{{ end }}
Var is {{ $var }}

A variable is first set globally and then it can be overwritten within different contexts.

However it seems that the opposite is not possible.

For example, if I set a variable within a specific range context then I cannot access it on the outside without .Scratch.

Is that correct? Or am I doing something wrong?

Thanks!

So, the new feature allows variable overwrites, but there are still scoping in play here – similar to how it would work in plain Go code. To cut a long story short, you need to initialize the variable in (or on the outside of) the scope where you intend to use it. Set it to some empty value if you’re not sure that it will be used.

{{ $var := "" }}
{{ if .IsHome }}
	{{ $var = "Hugo Home" }}
{{ end }}
Var is {{ $var }}
3 Likes

Thanks for the explanation. I will check it out tomorrow morning and post my findings.

Ok. So the following works as suggested above:

    {{ $var := "" }}
{{ if .IsHome }}
	{{ $var := "Hugo Home" }}
	Var is {{ $var }}
	{{ else }}
	{{ $var := "Not Home" }}
	Var is {{ $var }}
{{ end }}

Yes. Standard scoping issues are at play here and $var would still be empty outside the conditions because it was set empty globally.

Also for more advanced use cases such as storing parameter keys from a specific set of pages .Scratch is still the only way to store those and access them on the outside.

Your example isn’t correct. Look at this:

{{ $var := "" }}
{{ if .IsHome }}
	{{ $var = "Hugo Home" }}
	{{ else }}
	{{ $var = "Not Home" }}
{{ end }}
Var is {{ $var }}
1 Like

Aha! Thanks a lot for clear this up.

However as I said above .Scratch is still pretty valuable for more advanced use cases.

1 Like