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

The following pug script:

- data = [ "A", "B", "C", "D" ]
- for (i=0,i<data.length;i++)
-  var even = (i%2)==0
   if even
     .row
       .col #{data[i]}
   else
       .col #{data[i]}

      

gives:

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

      

I want to:

<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>

      

Why is the else block not indented? How to achieve the desired result?

+3


source to share


2 answers


The pug, by its very nature, does not allow such "extra" indentation in the block else

. To achieve the desired result, you can think of 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]}

      



what gives -

<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>

      

+1


source


While sean's answer is correct, it contains code duplication because you need to specify what you want to do with the element twice per line. His answer also doesn't scale well for situations where you need more than two items per line.

Instead of using the [i + 1] by sean structure, I would suggest using a second loop to find all the elements that should fall into this string. This can be done using the following template:

- 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 string if (j - i >= 0 && j - i < itemsPerRow)

makes sure that only elements that actually fall into that string get rendered.



This avoids duplication of code as you only need to enter once .. What you want to do with -item- ..

.

The result looks like this

.row
  .col
  .col
.row
  .col
  .col
.row
  .col
  .col

      

+1


source







All Articles