大多数Liquid"过滤器"实际上是函数编程意义上的"映射":您获取一个数组,将一个函数应用于每个元素,并返回转换后的数组。相反,我想"筛选":我只想返回数组中符合特定条件的项。我该怎么做?
具体来说,我正在努力改进这个模板:
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.
我该怎么解决这个问题?
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 %}
为什么液体社区如此反对压痕我不知道。。