Skip to content

Instantly share code, notes, and snippets.

@metaskills
Created July 24, 2012 14:47
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save metaskills/3170386 to your computer and use it in GitHub Desktop.
Save metaskills/3170386 to your computer and use it in GitHub Desktop.
Mapping A Sass List To A Comma Separated Selector
// Using this code below, I was able to itterate over a list of
// color names and append them to an empty list. I was then able
// to use the selectors from there.
$selectors: ();
@each $value in $my-colors-names {
$selector: unquote(".box.#{$value} .box-header");
$selectors: append($selectors, $selector, comma);
}
#{$selectors} { @extend .color-white; }
// However, I would like to make a function that helps with this
// task. Something like this below. The first problem is that I
// need a way to evaluate the `$interpolation` during the each
// block. I have not yet looked to see if there is a `sub()`
// function or some way I can make that a template.
@function map-to-selectors($list, $interpolation) {
$selectors: ();
@each $value in $list {
$selector: unquote($interpolation);
$selectors: append($selectors, $selector, comma);
}
@return $selectors
}
$selectors: map-to-selectors($my-colors-names, ".box.#{$value} .box-header");
// Thoughts? Better ways to use this along side the additional
// functions provided by Compass? A way to lazy eval the template?
@metaskills
Copy link
Author

Any thoughts? @chriseppstein

@metaskills
Copy link
Author

OK, here is my solution to my own problem. First, this relies on using this custom #gsub Sass extension.

module Sass::Script::Functions
  def gsub(string, regexp, replacement)
    Sass::Script::String.new(string.value.gsub(Regexp.new(regexp.value), replacement.value))
  end
end

From here, I made an @mixin vs and @function so that I could leverage Sass 3.2's new @content feature.

@mixin map-to-selectors($list, $template) {
  $selectors: ();
  @each $value in $list {
    $selector: unquote(gsub($template, '\{\{VALUE\}\}', $value));
    $selectors: append($selectors, $selector, comma);
  }
  #{$selectors} { @content; }
}

From here, I can now write Sass like this which maps a Sass list to an array of selectors. Then using @content and Sass' @extend with placeholder selectors aka, silent presentation classes, yields some epic win!

@include map-to-selectors($my-colors-names, '.box.{{VALUE}} .box-header') { @extend %color-white; };

@zinkkrysty
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment