Filtering an array in a Liquid / Jekyll template

Most fluid "filters" are actually "maps" in the sense of functional programming: you take an array, you apply a function to each element, and you return the transformed array. I would like to "filter" instead: I want to return only those elements in the array that match a certain condition. How can i do this?

Specifically, I'm trying to improve this pattern:

Authors: 
{% for c in site.data["contributors"] %}
  {% assign contributor = c[1] %}{% if contributor.role contains "author" %}{{contributor.name.given}} {{contributor.name.family}}{% endif %}{% endfor %}

      

which, in preference, looks like this:

Authors: 
{% for c in site.data["contributors"] %}
  {% assign contributor = c[1] %}
  {% if contributor.role contains "author" %}
    {{contributor.name.given}} {{contributor.name.family}}
  {% endif %}
{% endfor %}

      

where its data looks like this:

ianbarber:
  name:
    given: Ian
    family: Barber
  org:
    name: Google
    unit: Developer Relations
  country: UK
  role:
    - engineer
  homepage: http://riskcompletefailure.com
  google: +ianbarber
  twitter: ianbarber
  email: ianbarber@google.com
  description: "Ian is a DRE"

samdutton:
  name:
    given: Sam
    family: Dutton
  org:
    name: Google
    unit: Developer Relations
  country: UK
  role:
    - author
  google: +SamDutton
  email: dutton@google.com
  description: "Sam is a Developer Advocate"

      

(example taken from here ).

The problem with this approach is that a newline is outputted if the current element does not match, as you can see at https://developers.google.com/web/humans.txt .

How can I fix this?

+3


source to share


2 answers


If you want to get rid of the newline if the condition doesn't match, try removing unnecessary linefeeds in sentences if

and for

:

{% for c in site.data["contributors"] %}{% assign contributor = c[1] %}{% if contributor.role contains "author" %}
  {{contributor.name.given}} {{contributor.name.family}}{% endif %}{% endfor %}

      



The source may not sound very nice, but it will probably get rid of the newline in the output.

Note. I haven't tried this, but reordering like this helped me get rid of unwanted translation strings. You may even have to place it {% if ...

on the far left, so the indent is not included.

+3


source


Jekyll 2.0 has a filter where

. See docs . An example is from the doc:



{{ site.members | where:"graduation_year","2014" }}
{{ site.members | where_exp:"item", "item.graduation_year == 2014" }}

      

+2


source







All Articles