大多数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 %}
Run Code Online (Sandbox Code Playgroud)
美化,看起来像这样:
Authors:
{% for c in site.data["contributors"] %}
{% assign contributor = c[1] %}
{% if contributor.role contains "author" %}
{{contributor.name.given}} {{contributor.name.family}}
{% endif %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
其数据如下所示:
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"
Run Code Online (Sandbox Code Playgroud)
(例子来自这里).
此方法的问题在于,如果当前元素与条件不匹配,则会输出换行符,如https://developers.google.com/web/humans.txt中所示.
我怎样才能解决这个问题?
Jekyll 2.0有一个where过滤器.查看文档.示例 - 来自doc:
{{ site.members | where:"graduation_year","2014" }}
{{ site.members | where_exp:"item", "item.graduation_year == 2014" }}
Run Code Online (Sandbox Code Playgroud)
如果您想在条件不匹配时删除换行符,请尝试删除ifandfor子句中不需要的换行符:
{% for c in site.data["contributors"] %}{% assign contributor = c[1] %}{% if contributor.role contains "author" %}
{{contributor.name.given}} {{contributor.name.family}}{% endif %}{% endfor %}
Run Code Online (Sandbox Code Playgroud)
这在源代码中看起来可能不太好,但它可能会消除输出中的换行符。
注意:我没有尝试这样做,但类似的重新排列帮助我摆脱了不需要的换行符。您甚至可能必须将 放在{% if ...最左边,这样缩进就不会被包括在内。