Sass variable interpolation with backslash in output

自闭症网瘾萝莉.ら 提交于 2019-12-05 03:46:44

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"; 
}   

If you include the backslash in the actual variable, then when the sass generates the css, it will actually generate the calculated unicode character instead of outputting the unicode in the css output. This still usually works but it's hard to debug if something is going wrong and it is a bit more prone to cause issues in the browser in rendering the icon.

To output the actual unicode in the generated CSS, you can do this:

@function icon($character){
    @return unquote('\"') + unquote(str-insert($character,'\\', 1)) + unquote('\"');
}

$icon-thing: "e60f";

.icon-thing:before {
    content: icon($icon-thing); //outputs content: "\e60f";
}

I got this to work by messing with the interpolation

sassmesiter demo

// ----
// Sass (v3.4.21)
// Compass (v1.0.3)
// ----

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

@each $icon in $icons {
    .icon-#{nth($icon, 1)}, 
    %icon-#{nth($icon, 1)} {
        content: #{'"\\' + nth($icon, 2) + '"'}; // <------ See this line
    }
}

compiles to

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

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

.icon-weather {
  content: "\602";
}

If you are using Gulp to compile your Sass files, installing this Gulp plugin is probably the easiest way to get around the issue:

https://www.npmjs.com/package/gulp-sass-unicode

var sass = require('gulp-sass');
var sassUnicode = require('gulp-sass-unicode');

gulp.task('sass', function(){
  gulp.src('style.scss')
    .pipe(sass())
    .pipe(sassUnicode()) // <-- This is the bit that does the magic
    .pipe(gulp.dest( "css/" ));
});

There is no need to make any code alterations in your Sass files. Write out your Sass code how you want and the unicode characters are decoded back into regular escaped strings in the output CSS automatically.

Input SCSS

$testContent: "\f26e";

#test {
  content:  $testContent;
}

Output CSS

#test {
  content: "\f26e";
}

Unfortunately, these solutions were not entirely working for me but I was finally able to get it working with SASS maps

//node-sass 4.11.0
//libsass 3.5.4

$hexes: (
           checkmark: \2714
        );

@function out-content($var) {
    @return unquote("\"#{ $var }\""); 
}

@each $mod, $code in $hexes {    
    .#{$mod}-after {
        &:after {
            content: out-content($code);
        }
    }
}

//output
//.checkmark-after:after {
    //content: "\2714";
//}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!