Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an array from a forloop?

I have a folder of images that I'd like to render on a page. I'd like these images to be ordered/filtered a particular way. To do that, I understand that the images need to first be together in an array.

I therefore start with an empty array:

{% assign my_array = "" %}

I then loop through the image folder, and attempt different ways of pushing each image into my_array. Example:

{% for image in site.static_files %}
  {% if image.path contains "assets/images/target-folder" %}
     <!-- Push image into array -->
     {{ my_array | push: image }}
  {% endif %}
{% endfor %}

Ideally, I can then use this array as intended:

{% for image in my_array | sort:"date" | reverse %}
  <!-- show image -->
{% endfor %}

I'm aware that I could make a data file with the images, but I'd like to avoid needing to take that extra step. Thanks for reading.

like image 495
Danny Avatar asked Aug 28 '17 20:08

Danny


1 Answers

You are almost there, the way of how you are creating the array it is the only thing to fix.

This {% assign my_array = "" %} creates an empty string. One easy way to create an array in Liquid is to split the above:

{% assign my_array = "" | split: ',' %}

Now you can push items into the array inside a for loop in the following way:

{% for image in site.static_files %}
  {% if image.path contains "assets/images/target-folder" %}
     <!-- Push image into array -->
     {% assign my_array = my_array | push: image %}
  {% endif %}
{% endfor %}
like image 66
marcanuy Avatar answered Sep 23 '22 07:09

marcanuy