Search code examples
sassinterpolationicon-fonts

Sass variable interpolation with backslash in output


I'm creating some icon font rules for using in my site. Using Sass I wanted to list all the icons in a list variable and use @each to loop through them all.

Code looks like this:

$icons: 
    wifi 600,
    wifi-hotspot 601,
    weather 602;

@each $icon in $icons {
    .icon-#{nth($icon, 1)}, 
    %icon-#{nth($icon, 1)} {
        content: "\#{nth($icon, 2)}";
    }
}

The problem is the backslash on the content: line. I need it for the character encoding, but it escapes the variable interpolation, outputting CSS that looks like this:

.icon-wifi {
  content: "\#{nth($icon, 2)}";
}

Adding one more backslash like this: content: "\\#{nth($icon, 2)}"; outputs this CSS:

.icon-wifi {
  content: "\\600";
}

Is there a way to get the Sass to output CSS with only a single backslash while keeping the variable interpolation?


Solution

  • You can add the backslash to the parameter in the $icons variable. That is,

    $icons: wifi "\600", wifi-hotspot "\601", weather "\602";
    
    @each $icon in $icons {
      .icon-#{nth($icon, 1)}, %icon-#{nth($icon, 1)} {
        content: "#{nth($icon, 2)}";
      }
    }
    

    Generated CSS:

    .icon-wifi {
      content: "\600"; 
    }
    
    .icon-wifi-hotspot {
      content: "\601"; 
    }
    
    .icon-weather {
      content: "\602"; 
    }