Shortcode "Container with Title" & if parm exists Help

I am trying to make a shortcode that wraps text into a div container that has style appled to a title heading and the paragraph text.

The goal here is that I want to check for a parameter “url” and if it exists then style the heading code with link markup. I have no idea how to use shortcode statements but below is the code. Maybe someone can point out where I going wrong. The shortcode is not rendering at all so I must be missing something:

shortcode example:

{{% alert title="This is a container header" url="/path/" %}}
This is the container text
{{% /alert %))

alert.html:

 <div class="alert-container">
  <h4>
    {{.Get "title"}}
    {{ if isset .Params "url" }}
    {{ with .Get "url" }}<a href="{{.}}">{{.Get "title"}}{{ end }}</a>
  </h4>
  {{ .Inner }}
</div>

You are missing a closing {{ end }} for the if block.

if isset .Params "url" and with .Get "url" both do similar things, which is to check whether a “url” parameter is passed through.

Try this instead (untested):

{{ .Get "title" }}
{{ if isset .Params "url" }}
  <a href="{{ .Get "url" }}">{{ .Get "title" }}</a>
{{ end }}

You can read more about shortcode templates here: https://gohugo.io/templates/shortcode-templates/

And general templating here: https://gohugo.io/templates/introduction/

Ok you got me on the right track. that worked but it duplicated the title. The below code works for me:

<div class="alert-container">
  <h4>    {{ if isset .Params "url" }}
    <a href="{{ .Get "url" }}">{{.Get "title"}}</a>
    {{else}}
    {{.Get "title"}}
    {{ end }}
  </h4>
  {{ .Inner }}
</div>

Is there a way to check for both params “title” and “url” and if they both dont exist only print the {{ .Inner }} part.?

Please read the the templates intro in the docs, especially the conditionals section: https://gohugo.io/templates/introduction/#conditionals

{{ if and (isset .Params "url") (isset .Params "title" ) }} <-- both set
  <a href="{{ .Get "url" }}">{{.Get "title"}}</a>
{{ else if (isset .Params "title" ) }}                      <-- only title set
  {{.Get "title"}}
{{ else }}                                                  <-- neither set
  {{ .Inner }}
{{ end }}

Will do. Thank you for pointing me in the right direction.

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