Hello,
I am new to Hugo and I am trying to create a new theme from scratch also writing a theme tutorial in the process. I have read the documentation, but still have some minor issues. Here is one of them:
I am trying to set a subtitle for each post so in the preamble i have:
+++
subtitle = "fancy subtitle"
+++
In post.html
I have the following code:
{{ if (isset .Params "subtitle") and (.Params.subtitle "!=" "") }}
<h2>{{ .Params.subtitle }}</h2>
{{ end }}
This works fine, but always leaves an empty h2 tag in the source html if subtitle = ""
in the preamble.
However the following code works perfectly without leaving empty tags:
{{ if (isset .Params "subtitle") and (.Params.subtitle "!=" "") }}
{{ with .Params.subtitle }}
<h2>{{ . }}</h2>
{{ end }}
{{ end }}
I cannot figure out why this is happening.
Thank you!
Have you tried just using the internal with statement and completely removing the isset?
{{with .Params.subtitle}}
<h2>{{.}}</h2>
{{end}}
HTH
Thank you for your answer. It is working fine with with
:
{{ with .Params.subtitle }}
<h2>{{ . }}</h2>
{{ end }}
It is also working without empty tags just omitting isset
:
{{ if ( .Params.subtitle ) and ( .Params.subtitle "!=" "") }}
<h2>{{ .Params.subtitle }}</h2>
{{ end }}
and also not checking if the parameter is empty:
{{ if .Params.subtitle }}
<h2>{{ .Params.subtitle }}</h2>
{{ end }}
Still clueless why this is happening.
In case it’s a bug, I am running Hugo v0.16.
Thanks @rdwatters
I tried this to check for one empty variable and use another inside the with loop. But that doesn’t work.
{{with .Params.subtitle}}
<h2>{{.}}</h2> <p>{{ .Params.foo }} </p>
{{end}}
Is there a way to call a second var?
This is because inside the with block the . no longer refers to the page anymore, it refers to the subtitle parameter only.
I usually store a reference to the page in a variable to get access to it inside of a nested scope such as with or range.
EX:
{{- $thisPage := . -}}
{{with .Params.subtitle}}
<h2>{{.}}</h2> <p>{{ $thisPage.Params.foo }} </p>
{{end}}
Hope this helps.
1 Like
@whippersnapper please do not reopen years-old topics. If you still have questions, please read Requesting Help and open a new topic.