Search code examples
loopssassbourbon

Simplifying SASS @include's to a loop?


I have this piece of code that is the most advanced SASS code I've built so far. Now I'm wondering if it could be simplified using some sort of loop for the @includes, but I'm having a bit of a brain freeze. Is it possible to add some kind of $n++?

@mixin child($n, $d, $t1: null, $t2: null) {
  &:nth-child(#{$n}) {
    @include animation-delay(#{$d}s);
    @if variable-exists(#{$t1}) {
      @include transform(translate(#{$t1}px,#{$t2}px));
    }
  }
}

@include child(1, 0.9);
@include child(2, 1.1, 18, 13);
@include child(3, 1.3, 35, 25);
@include child(4, 1.1, 18, 38);
...

At first I thought of putting the @mixin in the loop, but that has to be way to complex. Some easier way?

Cheers


Solution

  • You could use a children() mixin, which would take a list in argument:

    @mixin child($n, $d, $t1: null, $t2: null) {
      &:nth-child(#{$n}) {
        @include animation-delay(#{$d}s);
        @if variable-exists(#{$t1}) {
          @include transform(translate(#{$t1}px,#{$t2}px));
        }
      }
    }
    
    @mixin children($children) {
      $n: 1;
      @each $child in $children {
        $d: nth($child, 1);
        $t1: null;
        $t2: null;
        @if length($child) > 1 {
          $t1: nth($child, 2);
          $t2: nth($child, 3);
        }
        @include child($n, $d, $t1, $t2);
        $n: $n+1;
      }
    }
    
    @include children((
      (0.9),
      (1.1, 18, 13),
      (1.3, 35, 25),
      (1.1, 18, 38)
    ));
    

    Notice the doubled parenthesis.

    Side note

    You're using variable-exists() in a wrong way. First, you must pass the variable name, not the variable itself :

    @if variable-exists(t1) { ... }
    

    Second, not sure, but I think you should use this line instead :

    @if $t1 != null { ... }
    

    The $t1 variable value can be null, but the variable itself will always exist. So I think your @if doesn't work.