如何从forloop创建数组?

时间:2017-08-28 20:12:00

标签: arrays jekyll liquid

我有一个我想在页面上呈现的图像文件夹。我希望以特定方式对这些图像进行排序/过滤。要做到这一点,我知道图像需要首先在一个数组中。

因此我从一个空数组开始:

{% assign my_array = "" %}

然后我循环浏览图片文件夹,尝试以不同方式将每张图片推入 my_array。例如:

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

理想情况下,我可以按预期使用此数组:

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

我知道我可以制作包含图片的数据文件,但我希望避免采取额外的步骤。谢谢你的阅读。

2 个答案:

答案 0 :(得分:12)

你几乎就在那里,你是如何创建阵列的,这是唯一需要解决的问题。

{% assign my_array = "" %}创建一个空字符串。在Liquid中创建数组的一种简单方法是拆分上面的内容:

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

现在,您可以通过以下方式将项目推送到for循环内的数组中:

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

答案 1 :(得分:3)

还请注意,您可以使用where/where_exp filters进行循环

  {% assign my_array = site.static_files | 
      where_exp: "item", "item.path contains 'assets/images/target-folder'" %}

或:

  {% assign target_folder = "assets/images/target-folder" %}
  {% assign my_array = site.static_files | 
      where_exp: "item", "item.path contains target_foler" %}

(尽管与接受的答案不同,它与问题的 title 并不完全对应,在描述的示例中仍然是一个有用的选项。)