antyakushev/postcss-for

Feature Request: Support for...in loop

fengyuanchen opened this issue · 2 comments

For example:

Input:

@for size in ['sm', 'md', 'lg'] {
  @for span from 1 to 4 {
    .col-$(size)-$(span) {
      width: calc(($(span) / 4) * 100)%;
    }
  }
}

Output:

.col-sm-1 {
  width: 25%;
}
.col-sm-2 {
  width: 50%;
}
.col-sm-3 {
  width: 75%;
}
.col-sm-4 {
  width: 100%;
}
.col-md-1 {
  width: 25%;
}
.col-md-2 {
  width: 50%;
}
.col-md-3 {
  width: 75%;
}
.col-md-4 {
  width: 100%;
}
.col-lg-1 {
  width: 25%;
}
.col-lg-2 {
  width: 50%;
}
.col-lg-3 {
  width: 75%;
}
.col-lg-4 {
  width: 100%;
}
@for size in ['sm', 'md', 'lg'] {
  @for span from 1 to 4 {
    .col-$(size)-$(span) {
      width: calc(($(span) / 4) * 100)%;
    }
  }
}

The JavaScript-style array syntax shouldn't be used here. Lists in CSS are either space separated or comma separated and they don't use brackets to enclose the list.

I think the for...in syntax should try to match the normal CSS syntax as much as possible. So we should use either space-separated lists or comma-separated lists.

My suggestion would be to use a comma-separated list like this:

@for $size in sm, md, lg {
  @for $fibonacci in 1, 2, 3, 5, 8 {
    .col-$(size)-$(fibonacci) {
      width: calc($fibonacci / 8 * 100%);
    }
  }
}

Why? Because using commas allows us to easily have a list of quoted values, like this:

@for $url in "http://example.com", "https://example.com" {
  a[href=$(url)] { color: green; }
}

And to have quoted values containing spaces or commas. You could also use single quoted values that contain double quote marks and vice versa.

@for $name in "Jane Doe", "Chris O'Connor", '12" pipe' {
  input[value=$(name)]::after { content: "Ok."; }
}

Fortunately PostCSS's list.comma() does the hard work for us.

Isn't this just postcss-each?