HUGO

Filtering data in JSON using `where`

Hi! I’ve got a JSON file with, say, data about sponsors. This JSON is placed within the data directory. The contents are something like this:

{
    "three": {
        "logo": "/images/sponsors/pt-spon-three.png",
        "class": "Platinum",
        "url": ""
    },
    "four": {
        "logo": "/images/sponsors/pt-spon-four.png",
        "class": "Platinum",
        "url": ""
    },
    "six": {
        "logo": "/images/sponsors/gl-spon-one.png",
        "class": "Gold",
        "url": ""
    },
}

I am trying to split the sponsors on my page using a partial. The partial is like:

<h5>Platinum Sponsors</h5>
<div class="block text-center">
    <!-- Sponsors image list -->
    <ul>
        {{ range where .Site.Data.sponsors "class" "Platinum" }}
        <li>
            <div class="image-block">
                <a href="{{ .url }}">
                    <img src="{{ .logo }}">
                </a>
            </div>
        </li>
        {{ end }}
    </ul>
</div>
<h5>Gold Sponsors</h5>
<div class="block text-center">
    <!-- Sponsors image list -->
    <ul>
        {{ range where .Site.Data.sponsors "class" "Gold" }}
        <li>
            <div class="image-block">
                <a href="{{ .url }}">
                    <img src="{{ .logo }}">
                </a>
            </div>
        </li>
        {{ end }}
    </ul>
</div>

Nothing gets displayed on the page on including this partial. When I remove the where clause, the list of sponsors shows, except, (obviously) it’s not filtered based on the class.

Could someone please point me in the right direction to get where working with data entries? I’m missing something critical to the working of this, and am unable to find what.

Update: I tried using the same principle, except this time, I used YAML files instead of a JSON. The result is the same.

Your are trying to range through a map of maps. You need an array of maps. Something like:

[
  {
    "name": "three",
    "logo": "/images/sponsors/pt-spon-three.png",
    "class": "Platinum",
    "url": ""
  },
  {
    "name": "four",
    "logo": "/images/sponsors/pt-spon-four.png",
    "class": "Platinum",
    "url": ""
  },
  {
    "name": "six",
    "logo": "/images/sponsors/gl-spon-one.png",
    "class": "Gold",
    "url": ""
  }
]

I think this should work:

{{ range $key, $value := .Site.Data.sponsors }}
  {{ if eq $value.class "Platinum"}}
    ...
  {{ end }}
{{ end }}
1 Like

That’s it; thank you!

Worked like a charm as well. I’ll try to explore how to iterate over class also, in this case, rather than hard-coding it. :slight_smile:

Something like this perhaps?

{{ $classes := slice "Platinum" "Gold" "Silver" }}
{{ range $classes }}
    ...
{{ end }}

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