[英]Filtering an array in a Liquid/Jekyll 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 %}
美化后看起來像這樣:
Authors:
{% for c in site.data["contributors"] %}
{% assign contributor = c[1] %}
{% if contributor.role contains "author" %}
{{contributor.name.given}} {{contributor.name.family}}
{% endif %}
{% endfor %}
它的數據如下所示:
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"
(示例取自此處)。
這種方法的問題在於,如果當前元素與條件不匹配,則會輸出換行符,如您在https://developers.google.com/web/humans.txt 中所見。
我怎樣才能解決這個問題?
Jekyll 2.0 有一個where
過濾器。 請參閱文檔。 示例 - 來自文檔:
{{ site.members | where:"graduation_year","2014" }}
{{ site.members | where_exp:"item", "item.graduation_year == 2014" }}
如果您想在條件不匹配時刪除換行符,請嘗試刪除if
和for
子句中不需要的換行符:
{% for c in site.data["contributors"] %}{% assign contributor = c[1] %}{% if contributor.role contains "author" %}
{{contributor.name.given}} {{contributor.name.family}}{% endif %}{% endfor %}
這在源代碼中可能看起來不太好,但它可能會擺脫輸出中的換行符。
注意:我沒有嘗試這個,但類似的重新排列幫助我擺脫了不需要的換行符。 您甚至可能需要將{% if ...
放在最左邊,因此不會包含縮進。
@Rudy Velthuis回答但縮進了..(由於隊列已滿,無法編輯答案)
{% for c in site.data["contributors"] %}
{% assign contributor = c[1] %}
{% if contributor.role contains "author" %}
{{contributor.name.given}}
{{contributor.name.family}}
{% endif %}
{% endfor %}
為什么液體社區如此再次縮進我不知道..
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.