【问题标题】:Loop through the first 3 items of an array in Liquid在 Liquid 中循环遍历数组的前 3 项
【发布时间】:2021-11-03 17:49:59
【问题描述】:

我正在创建一个网站,让您可以根据人们调查的信息浏览人们想要的礼物(我只会调查一小部分人,除非该网站有一些关注 - 我不担心创建一个非常大的网站上的列表,但这不是我要问的)。

我正在使用 Jekyll 对网站进行编码,所以我当然需要使用 Liquid。

你看,我想对 site.posts 数组中的前 3 项进行排序。

我查看了array filters documentation,但似乎找不到任何我需要完成的工作。

我阅读了this post,但我不完全确定如何理解那里的答案,因为我不知道“第三循环”是什么,而且我循环浏览帖子的方式不会使用site.posts[0]site.posts[1] 等可以很好地访问数组数据。这会使代码变得庞大,但我想如果需要的话我可以这样做。

这是我现在的代码:

<h2>Recently added gifts</h2>
<div class="posts">
    {% assign posts = site.posts %}
    {% for post in posts %}
    {% unless post.list  %}
    <div class="post">
        <h3 class="post-title">
            <a href="{{ post.url | relative_url }}">
                {{ post.title }}
            </a>
        </h3>

        <time datetime="{{ post.date | date_to_xmlschema }}" class="post-meta">{{ post.date | date_to_string }}</time>

        <p class="post-excerpt">
          {% if post.description %}
            {{ post.description | strip_html }}
          {% else %}
            {{ post.excerpt | strip_html }}
          {% endif %}
        </p>
    </div>
    {% endunless %}
    {% endfor %}
</div>

    

【问题讨论】:

  • 不确定您要在这里实现什么。要遍历数组中的 3 个第一次出现,您可以使用类似 {% for post in posts limit:3 %} 但我的猜测是您正在寻找更复杂的东西。您介意澄清一下您的问题吗?
  • 我试过 limit:3 ,它似乎工作。我不知道那存在。抱歉问了这么一个基本问题..
  • 没问题:)。我会将评论添加为答案,因为它可能对其他人有所帮助。

标签: arrays jekyll liquid


【解决方案1】:

正如评论中的解释和答案可能对其他人有所帮助,您可以在遍历数组时将限制设置为参数,如下所示:

{% for post in posts limit:3 %}
    Do something
{% endfor %}

【讨论】:

    猜你喜欢
    • 2021-11-19
    • 1970-01-01
    • 2017-09-26
    • 1970-01-01
    • 2021-08-12
    • 2014-06-04
    • 1970-01-01
    相关资源
    最近更新 更多