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

前端 未结 2 1250
旧巷少年郎
旧巷少年郎 2021-01-21 02:26

The following Pug script:

- data = [ \"A\", \"B\", \"C\", \"D\" ]
- for (i=0,i

        
相关标签:
2条回答
  • 2021-01-21 02:42

    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>
    
    0 讨论(0)
  • 2021-01-21 03:00

    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
    
    0 讨论(0)
提交回复
热议问题