[SOLVED] Should `with` fail when a variable isn't set?

From how I understand the with function, it checks to see if a variable is available and, when it is, executes the code between {{ with ..}} and {{ end}} – much like isset.

But that’s not what I’m seeing. In layouts/_default/section.html I have:

{{ with .Parent.Parent.Parent }}
	{{ .Title }}
{{ end }}

I would expect this code to show the title of the section a few levels up, provided those parents are present. (Since not every section page has that many parents.)

But that’s not what I get:

ERROR 2018/05/23 11:51:32 Failed to render "theme/_default/section.html": runtime error: invalid memory address or nil pointer dereference
Hugo Static Site Generator v0.40.3 windows/amd64 BuildDate: 2018-05-09T07:47:04Z
GOOS="windows"
GOARCH="amd64"
GOVERSION="go1.10.1"

Should I report this as a bug on GitHub? Or do I misunderstand how with works?

with doesn’t check if each variable in that 3-part variable exists. It assumes that the initial .Parent.Parent already exists, and checks only if the last .Parent in.Parent.Parent.Parent exists. The “nil reference” error would happen if either .Parent or .Parent.Parent is nil.

So maybe try:

{{ with .Parent }}
    {{ with .Parent }}
        {{ with .Parent }} 
            {{ .Title }}
        {{ end }}
    {{ end }}
{{ end }}
1 Like

Thanks! That code works.

But isn’t .Parent.Parent.Parent a 3-part variable? I at least always read such template code as “the .Parent variable from the .Parent variable from the .Parent variable”.

It is… I rephrased that “checks whole” statement for clarity.

1 Like