jekyll for 循环不显示 post 的标题

jekyll for loop don't show post's title

我在 _post 目录中有一些 post,我需要在浏览器中使用 Bootstrap(并使用 Jekyll)在两列中显示。这是我的代码:

{% capture cant_element %}{{ site.posts.size | divided_by:2 }}{% endcapture %}
{% for i in (0..cant_element) %}
<div class="row">
  <div class="col-md-6">
    {% capture new_i %}{{ i | times:2 }}{% endcapture %}
    {{ new_i }}
    {{ site.posts[new_i].title }}
  </div>
  <div class="col-md-6">
    {% capture new_i_plus %}{{ i | times:2 | plus:1 }}{% endcapture %}
    {{ new_i_plus }}
    {{ site.posts[new_i_plus].title }}
  </div>
</div>
{% endfor %}

我看不到(在浏览器中)变量 new_inew_i_plus 但不显示 post 标题 (site.posts[new_i_plus].title)

为什么?谢谢

您混淆了 captureassign 标签。

任意 {% capture %}any code here{% endcapture %} return 一个字符串。

所以当你试图通过他的索引号获取一个元素时,比如 {{ site.posts[new_i].title }} 其中 new_i 是一个字符串,就像做 {{ site.posts['0'].title }},它 return没什么,因为 '0' 字符串不是索引。

做一个像{% assign new_i = i | times:2 %}这样的作业会return一个Fixnum(一个数字)。您的 {{ site.posts[new_i].title }} 现在将转换为 {{ site.posts[0].title }} 并且会 return 一些东西,因为 new_i 是一个数字和一个真实的索引。

您的逻辑不会遍历所有 post(有时)

{{ site.posts.size | divided_by:2 }} 将 return 一个绝对值。如果你有 3 个 post,这将是 return 1,你的循环将总是忽略最后一个 post 的奇数索引。

完成任务的另一种方式

使用liquid iteration tags你可以更有效地做到这一点。

{% for p in site.posts %}
    {% assign isEven = forloop.index0 | modulo: 2 %}
    {% if isEven == 0 %}
        <div class="row">
            <div class="col-md-6">
                <h2>{{ site.posts[forloop.index0].title }}</h2>
            </div>
            {% if forloop.rindex0 > 0 %}
            <div class="col-md-6">
                <h2>{{ site.posts[forloop.index].title }}</h2>
            </div>
            {% endif %}
        </div>
    {% else %}
        {% continue %}
    {% endif %}
{% endfor %}