Conditionally checking for non existent variable

Hi!

I’m really lost in here. How can I check for a variable that isn’t always available?

{{ if or (.IsHome) (and .IsPage (eq .File.BaseFileName "running")) }}

I tried a lot of different codes, but… at <.File.BaseFileName>: File is not a field of struct type *hugolib.Node in partials/footer.html

I’m sorry. I still can’t find my way on GoLang.

Thank you.

There is a function called “with” that you can use. If the variable is set, then the code in the block will run. If it isn’t, then it will be skipped.

{{ with .File }}{{ with .File.BaseFileName }}
...something...
{{ end }}{{ end }}

There are some more examples in http://gohugo.io/templates/functions/

Thank you.

I can’t use with because I have two conditions: be the homepage or be the running page.

I saw that you edited your answer. My first try was using isset .File "BaseFileName" and it didn’t work too.

Thank you.

If .IsPage

Thank you for your attention.

I tried .IsPage together with .File.BaseFileName, but… No luck. The last condition is always evaluated and it crashes the code.

Yes, that is a curious effect of how Go templates and/or operator, I think. You must map the entire conditional in an if:

{{ if .IsPage }}
{{ if eq .File... }}
{{ end }}
{{ end }}

Thank you again.

However, your code emulates an AND, while I need an OR.

I tried to use a… Something like a ternary attribution, but it doesn’t work either.

{{ $fileName := .File.BaseFileName | default "" }}
{{ if or (.IsHome) (eq $fileName "running") }}

Ok! I found a way! If somebody has a better idea, please tell me.

{{ $fileName := "" }}

{{ if .IsPage }}
    {{ $fileName := .File.BaseFileName }}
{{ end }}

{{ if or (.IsHome) (eq $fileName "running") }}
[...]
{{ end }}

I don’t know why, but the attribution has to be this way. An {{ else }} gives the error undefined variable "$fileName":

{{ if .IsPage }}
    {{ $fileName := .File.BaseFileName }}
{{ else }}
    {{ $fileName := "" }}
{{ end }}

Thank you all!