【问题标题】:Jekyll / Liquid: Passing an Array into an Include and LoopingJekyll / Liquid:将数组传递到包含和循环中
【发布时间】:2019-03-19 21:42:07
【问题描述】:

我正在尝试遍历作为变量传递给包含的数组,然后检查该变量是否与某些 YAML 匹配——如果匹配,我想打印结果。我可以使用下面的代码手动执行此操作,但是我需要一个可以在给定更大数组的情况下工作的解决方案。

首先,我从页面传递这个信息:

<!--- Pass these variables into include.html --->

{% assign var_array = "D" %}
{% assign data = "object" %}
{% include include.html %}

我想消除所有 eslif 并替换为将循环整个数组的东西。

<!--- include.html --->

{% assign data = site.data.sheet.[data].last.items %}
{% assign sorted = var_array | split:"," %}

{% for item in data %}

    {% if item.foo == sorted[0] %}
    <p>{{ item.foo }}</p>

    {% elsif item.foo == sorted[1] %}
    <p>{{ item.foo }}</p>

    {% elsif item.foo == sorted[2] %}
    <p>{{ item.foo }}</p>

    {% elsif item.foo == sorted[3] %}
    <p>{{ item.foo }}</p>
    {% endif %}

{% endfor %}

这是 YAML 数据:

<!--- sheet.yaml --->

object:
- items:
  - foo: 'A'
  - bar: 'text'
- items:
  - foo: 'B'
    bar: 'text'  
- items:
  - foo: 'C'
    bar: 'text'  
- items:
  - foo: 'D'
    bar: 'text'      

这是所需的输出:

<!-- Desired Output --->

<p>D</p>

【问题讨论】:

标签: yaml jekyll liquid


【解决方案1】:

我认为你需要的是一个嵌套的for 循环。

这应该可以解决问题:

{% for item in data %}
    {% for s in sorted %}
        {% if item.foo == s %}
            <p>{{ item.foo }}</p>
        {% endif %}            
    {% endfor %}
{% endfor %}

如果您循环的两个数组很大,这将产生许多迭代。但是在 Jekyll 环境中,这只会在您开发项目的特定部分时执行。

顺便说一句:在您的代码中,您没有将任何变量传递给包含的文件。 查看 Jekyll 文档以了解如何正确执行此操作:https://jekyllrb.com/docs/includes/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-04
    • 1970-01-01
    • 2016-11-19
    • 1970-01-01
    • 1970-01-01
    • 2014-03-25
    • 2015-02-17
    • 1970-01-01
    相关资源
    最近更新 更多