skip to Main Content

I want to assign several @mixins to classes with the same name, something like:

@each $herramienta in $listaHerramientas {
    .#{$herramienta} {
        @include #{$herramienta};
    }
}

The compiler throws the error Expected identifier, which seems to mean the @include does not admit variables. Is that right? Is there a way to avoid writing all classes one by one?

2

Answers


  1. Yes, you’re correct that SCSS does not allow variables to be used directly as mixin names in the @include directive. However, there is a way to achieve this by using the @if or @else if conditions to include the appropriate mixin based on the value of the variable.

    $listaHerramientas: herramienta1, herramienta2, herramienta3;
    
    @mixin herramienta1 {}
    
    @mixin herramienta2 {}
    
    @mixin herramienta3 {}
    
    @each $herramienta in $listaHerramientas {
        .#{$herramienta} {
            @if $herramienta == herramienta1 {
                @include herramienta1;
            }
            @else if $herramienta == herramienta2 {
                @include herramienta2;
            }
            @else if $herramienta == herramienta3 {
                @include herramienta3;
            }
        }
    }
    Login or Signup to reply.
  2. Instead of using @include, you can use @use to import mixins from another module and then include them dynamically.
    
    In _mixins.scss, define your mixins like this:
        // _mixins.scss
        @mixin tool1 {
            // Your mixin styles for tool1
        }
    
        @mixin tool2 {
          // Your mixin styles for tool2
        }
        // ... and so on
    
    In your main SCSS file (e.g., styles.scss), use @use to import the _mixins.scss file:
        // styles.scss
        @use 'mixins' as *; // Import all mixins from _mixins.scss
    
        @each $herramienta in $listaHerramientas {
            .#{$herramienta} {
                 @include #{$herramienta}; // Include the mixin dynamically
           }
      }
    
    Make sure both files (_mixins.scss and styles.scss) are in the same directory.
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search