Fasani Fasani - 8 days ago 5
Less Question

Using LESS variables in HTML Data Attribute in "quotes"

I am currently converting code from SASS to LESS.

I have a problem with the following line of code:

&[data-rating = "@{counter - 0.5}"] { // THIS DOES NOT WORK


How can I work with variables and subtract 0.5 from my counter var and have it in a pair of quotes so that it can sit inside the HTML data attribute.

I have included two code examples so you can take the code and run it to see my results.

SASS:

.reviews-stars {
display: inline-block;

@for $i from 1 through 5 {
&[data-rating = "#{$i}"] {
.star:nth-child(-n + #{$i}):before {
color: green;
}
}

&[data-rating = "#{$i - 0.5}"] {
.star:nth-child(-n + #{$i}):before {
color: red;
}
}
}
}


LESS:

.looper-review-stars(@counter) when (@counter > 0) {

.looper-review-stars((@counter - 1)); // next iteration

&[data-rating = "@{counter}"] { // THIS WORKS
.star:nth-child(-n + @{counter}):before { // THIS WORKS
color: green;
}
}

// THIS DOES NOT WORK IT RETURNS THE STRING "@{counter - 0.5}"
&[data-rating = "@{counter - 0.5}"] { // THIS DOES NOT WORK
.star:nth-child(-n + @{counter}):before { // THIS WORKS
color: red;
}
}
}

.reviews-stars {
display: inline-block;
.looper-review-stars(5); // launch the loop
}

Answer

You can do it using a temporary variable like in the below snippet. Since selectors are strings I think it is better to keep all math operations away from it and in a separate statement.

.looper-review-stars(@counter) when (@counter > 0) {

  .looper-review-stars((@counter - 1)); // next iteration

  &[data-rating = "@{counter}"] { 
    .star:nth-child(-n + @{counter}):before { 
      color: green;
    }
  }

  @temp: @counter - .5; /* temporary variable */
  &[data-rating = "@{temp}"] { 
    .star:nth-child(-n + @{counter}):before { 
      color: red;
    }
  }
}

.reviews-stars {
  display: inline-block;
  .looper-review-stars(5); // launch the loop
}
Comments