【发布时间】:2014-10-20 18:12:09
【问题描述】:
大多数 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"
(示例取自here)。
这种方法的问题在于,如果当前元素不匹配条件,则会输出换行符,如您在https://developers.google.com/web/humans.txt 中所见。
我该如何解决这个问题?
【问题讨论】:
-
'大多数液体“过滤器”实际上是“地图”'+!。具有讽刺意味和令人讨厌的是,Liquid 的“过滤器”唯一不属于的部分是一个真正的 f#%$ing 过滤器!