简体   繁体   English

Jekyll / Liquid:将数组传递给包含和循环

[英]Jekyll / Liquid: Passing an Array into an Include and Looping

I'm trying to loop over an array that is passed into an include as a variable, and then check to see if the variable matches some YAML — if it does I want to print the result. 我试图循环一个作为变量传入include的数组,然后检查变量是否与某个YAML匹配 - 如果是,我想打印结果。 I can do this manually using the code below, however I need a solution that will work given a larger array. 我可以使用下面的代码手动执行此操作,但是我需要一个可以在给定更大数组的情况下工作的解决方案。

First, I pass through this information from the page: 首先,我从页面传递这些信息:

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

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

I want to eliminate all the eslif and replace with something that will loop over the whole array. 我想消除所有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 %}

Here's the YAML data: 这是YAML数据:

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

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

Here's the desired output: 这是所需的输出:

<!-- Desired Output --->

<p>D</p>

I think what you need is a nested for loop. 我认为你需要的是一个嵌套的for循环。

This should do the trick: 这应该做的伎俩:

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

If the two arrays you are looping over are large, this will produce many iterations. 如果循环的两个数组很大,这将产生许多迭代。 However in the Jekyll environment, this will only be executed while you are developing that particular part of the project. 但是在Jekyll环境中,这只会在您开发项目的特定部分时执行。

BTW: In your code you are not passing any variables to the included file. 顺便说一句:在你的代码中,你没有将任何变量传递给包含的文件。 Check the Jekyll documentation on how to do this correctly: https://jekyllrb.com/docs/includes/ 查看Jekyll文档,了解如何正确执行此操作: https//jekyllrb.com/docs/includes/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM