Range dict to test if vals are empty with a twist

This is easier to explain with code, so please follow along :wink:

Working - frontmatter keys are not empty

content/profiles/example.md

fruits = ["Banana", "Apple", "Pear"]
vegetables = ["Cucumber", "Pepper", "Lemon"]

layouts/profiles/example.html

  <div class="desc">
    {{$sections := (dict "1_Fruits" (delimit .Params.fruits ", ") "2_Vegetables" (delimit .Params.vegetables ", "))}}
    <div class="row">
      {{range $key, $val := $sections}}
      {{if $val}}
      <div class="large-4 columns end">
        <h3 class="product-heading">{{substr $key 2}}</h3>
        <h4 class="product-value">{{$val}}</h4>
      </div>
      {{end}}
      {{end}}
    </div>
  </div>

resulting html

<div class="desc">
  <div class="row">
    <div class="large-4 columns end">
      <h3 class="product-heading">Fruits</h3>
      <h4 class="product-value">Banana, Apple, Pear</h4>
    </div>

    <div class="large-4 columns end">
      <h3 class="product-heading">Vegetables</h3>
      <h4 class="product-value">Cucumber, Pepper, Lemon</h4>
    </div>

  </div>
</div>

Not working - frontmatter keys are empty

content/profiles/example.md

fruits = [""]
vegetables = [""]

resulting html

<div class="desc">
  <div class="row">
  </div>
</div>

desired html output

Nothing.

I’ve attempted to solve this by moving the range above <div class="desc"> but this has the undesired effect of creating multiple divs of class=“desc”.

Close, but no cigar. You want this:

fruits = []
vegetables = []

Lol no cigar is fine, but that still creates the html :cry:

<div class="desc">
  <div class="row">
  </div>
</div>

That’s what happens when I get in a hurry. :runner: What about something like this?

{{ if or (len .Params.fruits) (len .Params.vegetables) }}
  <div class="desc">
    <div class="row">
      {{ with .Params.fruits }}
      <div class="large-4 columns end">
        <h3 class="product-heading">Fruits</h3>
        <h4 class="product-value">{{ delimit . ", " }}</h4>
      </div>
      {{ end }}
      {{ with .Params.vegetables }}
      <div class="large-4 columns end">
        <h3 class="product-heading">Vegetables</h3>
        <h4 class="product-value">{{ delimit . ", " }}</h4>
      </div>
      {{ end }}
    </div>
  </div>
{{ end }}

Although, that first if may need some (gt (len .Params.fruits) 0) stuff to make it work.

1 Like

Hehe that helped me get to a working solution. Where do I send the cigars :yum:

1 Like