How to use a variable in another variable but only if it exists

This:

{{ $class := delimit .Attributes.class .AlertType " "}}

fails when there is neither a class attribute, nor it is an alert. How can I get it to define $class only if there is one or both of those ?

I would like to make the following works somehow:

{{ $author := $.Page.RenderString .Attributes.author  }}
{{ $class   := delimit .Attributes.class .AlertType " "}}
{{ $cite   := $.Page.RenderString .Attributes.cite }}
{{ $title   := default ($.Page.RenderString .Attributes.title) .AlertTitle }}

{{if or $cite $title}}
<figure {{with .Attributes.id}}id="{{.}}" {{end}} {{with $class}}class="{{.}}"{{end}}>{{with $title}}<figcaption>{{.}}</figcaption>{{end}}
<blockquote {{if in $cite "]("}}cite="{{strings.TrimSuffix ")" (index (last 1 (split $cite "](")) 0)}}"{{end}}>{{ .Text }}</blockquote>
<cite>{{with $cite}}{{.}}{{end}}{{with $author}} — {{.}}{{end}}</cite>
</figure>
{{else}}
<blockquote {{with .Attributes.id}}id="{{.}}" {{end}}{{with $class}}class="{{.}}"{{end}}>{{ .Text }}</blockquote>
{{end}}

Out of curiosity, why are you delimiting a string (.Attributes.class)?

{{ delimit "aa" "b" }} → "97b97" (string)
1 Like

ah… that’s it, what I wanted is

{{ $class := delimit (slice .Attributes.class .AlertType) " "}}

This feature is very nice.

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