.Scratch was necessary before Go allowed rebinding template variables. Now, it's not strictly necessary, but Hugo includes it for backwards compatibility, plus it has some nicer APIs (e.g. for building dictionaries with .SetInMap).
Brian Rinaldi is a Developer Experience Engineer at LaunchDarkly with over 20 years experience as a developer for the web. Brian is active in the community running CFE.dev and Orlando Devs.
Thanks for the comment. Yes, I had this discussion with someone who reviewed my article and I think that in most cases it can be avoided but 1) sometimes its just easier to use it; and 2) I have run into cases where I can't seem to remove it (or if I could, it goes back to 1). My use case is simple for example purposes, but I have run into fringe cases where I tried refactoring Scratch out and simply could not fix the scoping any other way. Here's a snippet of the example:
{{ if ne .Params.sessions nil }}
{{ range $session := .Params.sessions }}
{{ with site.GetPage (print "/sessions/" $session) }}
{{ $.Scratch.Set "speakers" .Params.speakers }}
<h2>{{ .Title }}</h2>
{{ .Content }}
{{ end }}
{{ $speakers := $.Scratch.Get "speakers" }}
{{ range $speaker := $speakers }}
...
In this case, I seem to run into issues with $speakers regardless of where I initially set it. There may be a way to avoid Scratch but, honestly, is it worth the pain of figuring out where the scoping issue is.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
.Scratch was necessary before Go allowed rebinding template variables. Now, it's not strictly necessary, but Hugo includes it for backwards compatibility, plus it has some nicer APIs (e.g. for building dictionaries with .SetInMap).
Thanks for the comment. Yes, I had this discussion with someone who reviewed my article and I think that in most cases it can be avoided but 1) sometimes its just easier to use it; and 2) I have run into cases where I can't seem to remove it (or if I could, it goes back to 1). My use case is simple for example purposes, but I have run into fringe cases where I tried refactoring
Scratch
out and simply could not fix the scoping any other way. Here's a snippet of the example:In this case, I seem to run into issues with
$speakers
regardless of where I initially set it. There may be a way to avoidScratch
but, honestly, is it worth the pain of figuring out where the scoping issue is.