【问题标题】:Filtering an array in a Liquid/Jekyll template在 Liquid/Jekyll 模板中过滤数组
【发布时间】: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 过滤器!

标签: jekyll liquid


【解决方案1】:

Jekyll 2.0 有一个where 过滤器。见docs。示例 - 来自文档:

{{ site.members | where:"graduation_year","2014" }}
{{ site.members | where_exp:"item", "item.graduation_year == 2014" }}

【讨论】:

    【解决方案2】:

    如果您想在条件不匹配的情况下删除换行符,请尝试删除 iffor 子句中不需要的换行符:

    {% for c in site.data["contributors"] %}{% assign contributor = c[1] %}{% if contributor.role contains "author" %}
      {{contributor.name.given}} {{contributor.name.family}}{% endif %}{% endfor %}
    

    这在源代码中可能看起来不太好,但它可能会去掉输出中的换行符。

    注意:我没有尝试这样做,但类似的重新排列帮助我摆脱了不需要的换行符。您甚至可能必须将{% if ... 放在最左侧,这样就不会包含缩进。

    【讨论】:

    • 不,这不起作用。事实上,这就是他们在代码库中所做的,而我在我的问题中做了一些美化。我想我应该说添加这个警告。
    • 我更改了格式。再试一次。问题是 for 和 if 子句中有换行符,这些换行符会插入到您不想要它们的位置。它们只应插入您想要的位置。所以重新格式化代码应该去掉这些换行符。在我的代码中,我也必须对此进行试验,以避免换行。
    • 每个换行符和空格都会被插入,即使你认为它只是为了美化和格式化。我经常用换行符+数字替换换行符,看看哪个放在哪里。然后我在最终来源中删除我不想要的换行符(和数字)。
    【解决方案3】:

    @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 %}
    
    

    我不知道为什么流动社区如此反对缩进..

    【讨论】:

      猜你喜欢
      • 2016-03-11
      • 1970-01-01
      • 2017-04-25
      • 1970-01-01
      • 1970-01-01
      • 2018-05-14
      • 1970-01-01
      • 1970-01-01
      • 2021-05-11
      相关资源
      最近更新 更多