Skip to content

Instantly share code, notes, and snippets.

@tylergaw
Created June 8, 2014 22:03
Show Gist options
  • Save tylergaw/adc3d6ad044f5afac446 to your computer and use it in GitHub Desktop.
Save tylergaw/adc3d6ad044f5afac446 to your computer and use it in GitHub Desktop.
Generate a CSS ruleset for every layer of the current page of a Sketch document
var allLayers = sketch.doc.currentPage().layers();
function createRuleSetStr (layer) {
var str = '';
var selector = '.' + layer.name().toLowerCase().replace(/ /gi, '-');
var attrs = layer.CSSAttributes();
str += selector + ' {';
for (var i = 0; i < attrs.count(); i += 1) {
var declaration = attrs.objectAtIndex(i);
// Sketch adds a comment to each rule set that is the name of the layer.
// Don't include that.
if (declaration.indexOf('/*') < 0) {
str += '\n\t' + declaration;
}
}
str += '\n}';
return str;
}
function generateStyleSheet () {
var stylesheet = '';
for (var i = 0; i < allLayers.count(); i += 1) {
var layer = allLayers.objectAtIndex(i);
stylesheet += '\n\n' + createRuleSetStr(layer);
}
return stylesheet;
}
var styleSheetString = generateStyleSheet();
log(styleSheetString);
@frason
Copy link

frason commented Jul 23, 2014

Ok I figured out what was going on with my Sketch file. You can't have artboards and you can't have groups. Once I removed both of those it worked.

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