Sass列表分隔符与简洁@mixin编写:免引号传选择器问题
Solution for Passing Unquoted Selectors to Your Sass Namespace Mixin
Great question! The issue here is that when you pass .bar + .baz without quotes, Sass doesn’t treat it as a string—it parses it as a selector node (a special Sass data type), which your original str-replace function can’t process directly. Here’s how to adjust your mixin to handle unquoted selectors:
Modified Code
@mixin pre-assign($value) { $pre: $value !global; } @include pre-assign('foo'); @function str-replace($string, $search, $replace: '') { $index: str-index($string, $search); @if $index { @return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace); } @return $string; } @mixin pre($value) { // Convert the selector node to a string, then strip surrounding quotes and leading whitespace $value-str: str-slice(inspect($value), 2, -2); // Apply your namespace replacement logic $result: str-replace($value-str, '.', '.#{$pre}-'); // Output the final selector #{$result} { @content; } }
How to Use It
Now you can call the mixin without quotes, exactly as you wanted:
@include pre(.bar + .baz) { display: none; }
Compiled Output
.foo-bar + .foo-baz { display: none; }
Key Changes Explained
inspect($value): This function converts Sass’s selector node data type into a string representation. For.bar + .baz, it returns" .bar + .baz"(with leading space and surrounding quotes—output may vary slightly by Sass version, but the core behavior is consistent).str-slice(inspect($value), 2, -2): This strips the leading space and surrounding quotes from the string, leaving clean, unquoted selector text like.bar + .baz.- Original Replacement Logic: With a proper string in hand, your existing
str-replacefunction works as intended to prepend the namespace to each class selector.
Edge Case Testing
This fix handles common selector patterns seamlessly:
- Pseudo-classes:
@include pre(.bar:hover)compiles to.foo-bar:hover { ... } - Multi-class selectors:
@include pre(.bar.baz)compiles to.foo-bar.foo-baz { ... } - Child selectors:
@include pre(.bar > .baz)compiles to.foo-bar > .foo-baz { ... }
内容的提问来源于stack exchange,提问作者DanMad
相关产品推荐
相关产品推荐

