The If statement does not work with range?

I want to render this markdown data:

optheader: Optional
optional:
  - 

The idea is to render the optheader only if there is something in the optional. If there is not - the optheader should not be rendered.

Here is the html for that:

<div>
  {{ if .optional }}
  <h5>{{ .optheader }}</h5>
  <ul>
    {{ range .optional }}
    <li>{{ . }}</li>
    {{ end }}
  {{ end }}
  </ul>
</div>

It does not work. The optheader is rendered anyway, despite there is nothing in the optional.

But it works fine if instead of range there a regular method to output the data, for instance

<p>{{ .optional }}</p>

Strangely, the If condition should work no matter what output method is used.

Does anyone know how to make the If condition work with the range function?
Thanks!

The “optional” params list is not empty the way you set it up. The first value is empty, but the list has one value non the less.

This is one way to solve it:

<div>
  {{ if index .Params.optional 0 }}
  <h5>{{ .Params.optheader }}</h5>
  <ul>
    {{ range .Params.optional }}
    <li>{{ . }}</li>
    {{ end }}
  {{ end }}
  </ul>
</div>

I found the solution: if my “optional” section contains a dash (to remind me that it uses rangeable data), it has content, so the If logic does not consider it empty - hence the optheader is rendered.

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