How to check for nil pointer properly?

This doesn’t work

{{- if eq $m nil -}}
{{ return }}
{{- end -}} 
{{- $cont := chomp $m.Content -}}

as <$m.Content>: nil pointer evaluating resource.Resource.Content is thrown – exactly what I was trying to avoid.

{{- if not $m -}} doesn’t work either.

Apparently I’m missing something that everyone else knows. How to do it properly in a partial?

1 - May be try {{ if eq $m "nil" }}

2 - Not sure if the {{ return }} command is legit without return variable. And in any case {{ return $myvar }} is evaluate ONCE in the partial and is NOT affected by the go template logic.

See : Returning values from partials

1 Like

Short story: The return need to be the last statement in your template.

So, you need to do something ala:

{{ $result := "" }}
{{ with $m }}
{{ $result = .Content  }}
{{ end }}
{{ return $result }}
3 Likes

No-no, nil in brackets was my gotcha of yesterday :laughing:
Thanks for the link, it was quite an entertaining reading while walking in the local forest. It actually answers my question.

Arrogantly have I thought, there is nothing new to learn about return statements. Thanks a bunch, my partial now works they way it is supposed to.

I have seen this “return statement” confusion before – the short story, again, I implemented this crude version of “return” in 2 hours. Doing it the right way would have taken me hundreds, at least.

Yes, I’ve read this heated discussion thread, and I don’t want to re-ignite it. You are right: while less than perfect, it is far more useful than nothing. I’m not paying anything for the software, and use it while enjoying very efficient support.

One suggestion, though: since this behavior is rather unusual, the documentation should scream about it, and it won’t take long to accomplish. I might volunteer for the task once I’m done with my theme. Until then – thanks for the feature.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.