对于循环,将每两个帖子包装在一个div中 [英] For loop, wrap every two posts in a div

查看:63
本文介绍了对于循环,将每两个帖子包装在一个div中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我使用的是 Jekyll (使用

Basically, I am using Jekyll (which uses the Liquid templating language) and I am trying to write a for loop which wraps every two items in a div.

这是我当前的循环:

<div>
  {% for post in site.posts %}
    <a href="{{ post.url }}">{{ post.title }}</a>
  {% endfor %}
</div>

这样会输出四个帖子,

<div>
  <a href="#">Title</a>
  <a href="#">Title</a>
  <a href="#">Title</a>
  <a href="#">Title</a>
</div>

我对四个帖子的期望输出是:

My desired output for four posts is:

<div>
  <a href="#">Title</a>
  <a href="#">Title</a>
</div>

<div>
  <a href="#">Title</a>
  <a href="#">Title</a>
</div>

我该怎么做?

推荐答案

我知道我已经迟到了,但是我发现我觉得这是一个相当优雅的解决方案,不会让人感到笨拙.

I know I'm late to the game but I found what I feel is a fairly elegant solution that doesn't feel hacky.

使用for循环的limitoffset参数,我们可以一次迭代一行,每行N个帖子.

With for loop's limit and offset params, we can iterate one row at a time, N posts per row.

首先,我们计算需要枚举的行数:

First, we count the number of rows we'll need to enumerate over:

{% assign rows = site.posts.size | divided_by: 2.0 | ceil %}

相当于Ruby的是rows = (posts.size / 2.0).ceil(奇数排成一行).

The Ruby equivalent would be rows = (posts.size / 2.0).ceil (odd numbers get their own row).

接下来,我们将遍历行:

Next, we'll iterate over the rows:

{% for i in (1..rows) %}
  <div>

现在,我们需要使用(i - 1) * 2(使用forloop.index0)来计算收集偏移量:

Now we need to calculate the collection offset with (i - 1) * 2 (using forloop.index0):

  {% assign offset = forloop.index0 | times: 2 %}

然后,我们可以迭代从行的偏移量开始的帖子切片(相当于Ruby中的posts[offset, 2]):

Then we can iterate over the slice of posts starting at the row's offset (equivalent to posts[offset, 2] in Ruby):

    {% for post in site.posts limit:2 offset:offset %}
      <a href="{{ post.url }}">{{ post.title }}</a>
    {% endfor %}

关闭行div的元素并进行循环:

Close the row div element and for loop:

  </div>
{% endfor %}

就是这样!

在Ruby中,这将是:

In Ruby, this would be:

rows = (posts.size / 2.0).ceil # the number of rows
(1..rows).each do |i|
  offset = (i - 1) * 2
  # <div>
  posts[offset, 2].each do |post|
    # <a href="#{post.url}>#{post.title}</a>
  end
  # </div>
end

现在一起在液态中

{% assign rows = site.posts.size | divided_by: 2.0 | ceil %}
{% for i in (1..rows) %}
  {% assign offset = forloop.index0 | times: 2 %}
  <div>
    {% for post in site.posts limit:2 offset:offset %}
      <a href="{{ post.url }}">{{ post.title }}</a>
    {% endfor %}
  </div>
{% endfor %}

希望这对某人有帮助!

这篇关于对于循环,将每两个帖子包装在一个div中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆