Writing a simple custom lookup table in Sass
Recently in a project I have been required to create a simple style guide in Sass that would include all the brand colors, respond to change of colors easily and scale pretty straight-forward. Unfortunately, soon I found out that interpolation of string to a variable is not easy at all and maps that would map string to a variable are “somewhere in the future” of Sass.
After a fair amount of digging in news groups and trial-and-error experiments, I came up with a simple color lookup table for Sass using @function, nth() and index(). Performance of such a solution is not very good but it’s still worth it if you want to scale color scheme later on and have an automatically generated solution that works.
The markup of the color picker is as follows:
<ul class="colors">
<li data-color="brand_red"></li>
<li data-color="brand_blue"></li>
...
</ul>
And Sass generator looks like this:
$brand_red: #f20;
$brand_blue: #02f;
...
$color_names: brand_red, brand_blue, ...;
$color_values: $brand_red, $brand_blue, ...;
@function color-for($name) {
@return nth($color_values, index($color_names, $name));
}
@each $color in $color_names {
[data-color=#{$color}] { background: color-for($color); }
}
[data-color]:after { content: attr(data-color); }
This generates colored box with name of the color for every color in the $color_names / $color_values array set. I am still working on how to get rid of double array set up, but haven’t figured it yet. If you know the solution, feel free to ping me on Twitter and let me know.
