简体   繁体   中英

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. 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.

<!--- 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:

<!--- 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.

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.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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