DEV Community

Discussion on: Advanced Hugo Template Tips and Tricks

Collapse
 
carlmjohnson profile image
Carl Johnson

.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).

Collapse
 
remotesynth profile image
Brian Rinaldi

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.