【问题标题】:How do I create an array from a forloop?如何从 for 循环创建数组?
【发布时间】:2017-08-28 20:11:59
【问题描述】:

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

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

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

我知道我可以用图像制作一个数据文件,但我想避免采取额外的步骤。感谢阅读。

【问题讨论】:

    标签: arrays jekyll liquid


    【解决方案1】:

    你快到了,你创建数组的方式是唯一需要解决的问题。

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

    【讨论】:

    • 效果很好,谢谢。我已使用您的修复程序稍后对该数组进行排序,然后循环遍历该数组。像这样:{% assign sorted_my_array = my_array | reverse %}.
    • 这很好用,但是 jekyll 也没有在他们的文档中列出这个功能。
    • 让我澄清一下:push 函数在 Jekyll 或 Shopify 文档中无处可见。它做了它应该做的事情,但它是一个秘密功能。
    • @user3411192 对不起,我现在明白了,看看 Jekyll 文档中的“数组过滤器”:jekyllrb.com/docs/liquid/filters 你可以看看:push pop i> 和 shift.
    【解决方案2】:

    还请注意,您可以使用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" %}
    

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

    【讨论】:

      猜你喜欢
      • 2012-09-11
      • 2021-09-11
      • 2021-12-26
      • 2023-04-01
      • 2019-08-28
      • 1970-01-01
      • 2017-08-09
      • 2012-09-21
      • 2017-07-10
      相关资源
      最近更新 更多