matthewelsom
matthewelsom

Reputation: 944

Using a 'Where' filter in Jekyll to only return items that are not blank

I have a CSV data file that contains a list of projects. I would like to assign variables to filtered segments of the data - then loop through them.

Here I have tried to filter all projects to show only the projects that have been assigned a value in the global_priority field. If the project has no value I do not what it in the list.

I have tried using where_exp, but it returns everything. What is the best way to approach this? Is it possible to achieve this without using an if statement?

projects.csv

name,global_priority,region,region_priority
Project A,1,Global,
Project B,,Spain,1
Project C,2,UK,1

The loop

{% assign projects = site.data.projects %}
{% assign global_p = projects | where_exp: "item.global_priority", "item.global_priority != blank" %}

  {% for p in global_p %}
    <ul>
      <li>{{ p.global_priority }}</li>
      <li>{{ p.region }}</li>
      <li>{{ p.name }}</li>
    </ul>
  {% endfor %}

Upvotes: 1

Views: 509

Answers (1)

marcanuy
marcanuy

Reputation: 23982

There is a small mistake in the way you access the where_exp item, it should refer to the name you will use in the comparation: where_exp: "item"

Then:

{% assign global_p = site.data.projects | where_exp: "item", "item.global_priority" %}

{% for p in global_p %}
<ul>
  <li>{{ p.global_priority }}</li>
  <li>{{ p.region }}</li>
  <li>{{ p.name }}</li>
  </ul>
{% endfor %}

Outputs:

<ul>
  <li>1</li>
  <li>Global</li>
  <li>Project A</li>
  </ul>

<ul>
  <li>2</li>
  <li>UK</li>
  <li>Project C</li>
  </ul>

Upvotes: 1

Related Questions