2
@for $i from 1 through $layer-count {
    #layer-#{$i} { background: url('../layers/layer-#{$i}.png'); }
    // background images are named layer-0001.png and up
}

There must be a way to achieve this, but I haven't been able to find anything.

bernk
  • 1,155
  • 2
  • 12
  • 22
  • What do you want to achieve exactly?. Please, show us where you want to use zero-filled numbers in loop, surely there is another easier way to do it. Anyway, is something like [this](https://gist.github.com/Aloge/7581489/edit) what you're looking for? – Alex Guerrero Nov 21 '13 at 13:28
  • @AlexGuerrero see my edit. The question isn't if there is another way to get this to work. Of course there is. But what I want to know is if there is a way to zerofill an index variable in Sass. That's all. – bernk Nov 21 '13 at 13:48

1 Answers1

1

You could do something like this:

@function zerofill($i) { @return #{str-slice("0000",0,4 - str-length(#{$i}))}$i; }

@for $i from 1 through $layer-count {
    $i: zerofill($i); // now $i holds the zro-filled value for further use
    #layer-#{$i} { background: url('../layers/layer-#{$i}.png'); }
}

DEMO


Or the same with a more general function, that takes a length for the zero-filled value:

@function rep($n, $s: "0") {
    $out: $s;
    @while str-length($out) < $n { $out: $out + $s; }
    @return $out;
}
@function zerofill($i, $n) { @return #{rep($n - str-length(#{$i}))}$i; }

DEMO


Note:

To be able to use the string functions you need to run Sass v3.3, so I quickly rewrote the general function so that it works in older Sass versions (I threw in pow() too that is also already integrated in v3.3, so then you could just use the zerofill() part of this):

@function pow($b, $n) {
  $f: $b; @while $n > 1 { $f: $f * $b; $n: $n - 1; } @return $f;
}
@function zerofill($i, $n){
  $f: pow(10, $n - 1); $out: null;
  @while $f >= 1 {
    $out: $out#{floor($i / $f)}; $i: $i - floor($i / $f) * $f; $f: $f / 10;
  } @return $out;
}

DEMO

Martin Turjak
  • 20,896
  • 5
  • 56
  • 76
  • Sass version information would be helpful here, this does not compile using the current stable version. – cimmanon Nov 21 '13 at 16:02
  • in the Sassmeister demos that I included it says: Sass (**v3.3.0.rc.1**). Hope this helps. – Martin Turjak Nov 21 '13 at 18:16
  • 1
    @cimmanon the problem were the string functions that are implemented in v3.3 ... I rewrote the general `zerofill()` function now so that it works in Sass <3.3. – Martin Turjak Nov 21 '13 at 20:06
  • Hi @bernk. I was just checking back on my answers and saw that you did not accept this one. Does it not answer the question? Do you need any other insight? Please let me know if there is anything else you might want to know. Best! – Martin Turjak Sep 06 '14 at 21:17