Do the indents in an else block continue from the then block?

梦想的初衷 提交于 2019-12-01 21:31:26

Pug, by nature, doesn't allow that kind of "extra" indentation within the else block. To achieve your desired result, you could think about it like this—

- var data = [ "A", "B", "C", "D" ]

each datum, index in data
  if ((index % 2) == 0)
    .row
      .col #{datum}
      if (data[index + 1])
        .col #{data[index + 1]}

—which yields—

<div class="row">
  <div class="col">A</div>
  <div class="col">B</div>
</div>
<div class="row">
  <div class="col">C</div>
  <div class="col">D</div>
</div>

Although sean's answer is correct it does contain code duplication because you have to specify what you want to do with the item, twice per row. His answer also doesn't scale well for situations where you need more than two items per row.

Instead of using the [i+1] structure by sean's I would suggest using a second loop to find all the items that have to fall into this row. This can be done using the following pattern:

- var itemsPerRow = 2; // This can be any positive number
each unused, i in data
  if (i % itemsPerRow == 0)
    .row
      each item, j in data
        if (j - i >= 0 && j - i < itemsPerRow)
          .col
             .. What you want to do with -item- ..

The line if (j - i >= 0 && j - i < itemsPerRow) makes sure that only the items that actually fall into that row get render.

This avoids code duplication because you only have to type .. What you want to do with -item- .. once.

The result looks like this

.row
  .col
  .col
.row
  .col
  .col
.row
  .col
  .col
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!