Reputation: 373
Most Liquid "filters" are actually "map"s in the functional programming sense: you take an array, you apply a function to each element and return the transformed array. I'd like instead to "filter": I want to return only those items in the array that match a certain condition. How can I do that?
Specifically, I'm trying to improve this template:
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, prettified, 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: [email protected]
description: "Ian is a DRE"
samdutton:
name:
given: Sam
family: Dutton
org:
name: Google
unit: Developer Relations
country: UK
role:
- author
google: +SamDutton
email: [email protected]
description: "Sam is a Developer Advocate"
(example taken from here).
The problem with this approach is that a newline is output if the current element doesn't match the condition, as you can see in https://developers.google.com/web/humans.txt.
How can I fix this?
Upvotes: 7
Views: 8079
Reputation: 2438
@Rudy Velthuis answer But indented.. (Could not edit answer as the queue is full)
{% for c in site.data["contributors"] %}
{% assign contributor = c[1] %}
{% if contributor.role contains "author" %}
{{contributor.name.given}}
{{contributor.name.family}}
{% endif %}
{% endfor %}
Why liquid community so agains indentation I do not know..
Upvotes: 0
Reputation: 8550
Jekyll 2.0 has a where
filter. See docs. Example - from doc:
{{ site.members | where:"graduation_year","2014" }}
{{ site.members | where_exp:"item", "item.graduation_year == 2014" }}
Upvotes: 12
Reputation: 28806
If you want to get rid of the newline if the condition doesn't match, try to remove the unwanted newlines in the if
and for
clauses:
{% for c in site.data["contributors"] %}{% assign contributor = c[1] %}{% if contributor.role contains "author" %}
{{contributor.name.given}} {{contributor.name.family}}{% endif %}{% endfor %}
That may not look nice in the source, but it will probably get rid of the newline in the output.
Note: I didn't try this, but similar rearranging helped me get rid of unwanted newlines. You may even have to put the {% if ...
on the extreme left, so the indentation does not get included.
Upvotes: 4