SASS变量插值在输出中具有后斜线



我正在创建一些在我的网站中使用的图标字体规则。我想使用SASS列出列表变量中的所有图标,并使用@EACH循环浏览所有图标。

代码看起来像这样:

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

问题是content:行上的后斜线。我需要它来编码字符,但是它可以逃脱可变插值,输出看起来像这样的CSS:

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

添加一个这样的后斜线:content: "\#{nth($icon, 2)}";输出此CSS:

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

是否有一种方法可以在保持可变插值的同时将SASS带到只有一个后斜线的CSS?

我通过弄乱插值

来使它起作用

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

编译到

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

如果在实际变量中包括后斜线,则当Sass生成CSS时,它实际上将生成计算的Unicode字符,而不是在CSS输出中输出Unicode。这通常仍然有效,但是如果出现问题,很难进行调试,并且在浏览器呈现图标时会更容易引起问题。

要输出生成的CSS中的实际Unicode,您可以执行此操作:

@function icon($character){
    @return unquote('"') + unquote(str-insert($character,'\', 1)) + unquote('"');
}
$icon-thing: "e60f";
.icon-thing:before {
    content: icon($icon-thing); //outputs content: "e60f";
}

您可以将Backslash添加到$icons变量中的参数中。也就是说,

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

生成的CSS:

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

使用UnQuote和Double Slash

$ var:123→内容:" e123"

 content:#{unquote('"')+("\")+("e")+$var+unquote('"')};

如果您使用Gulp来编译SASS文件,则安装此Gulp插件可能是解决问题的最简单方法:

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

无需在SASS文件中进行任何代码更改。写出您的SASS代码,您想要的方式和Unicode字符被解码回输出CSS中的常规逃逸字符串。

输入SCSS

$testContent: "f26e";
#test {
  content:  $testContent;
}

输出CSS

#test {
  content: "f26e";
}

不幸的是,这些解决方案并不完全适用于我,但我终于能够与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";
//}

最新更新