Sunday, January 24, 2010

Groovy DSL for CSS (Part 1)

I decided to experiment with writing a DSL for CSS in Groovy. There are some other DSLs out there like SASS but I think the syntax is almost worse than writing normal CSS and it definitely doesn't look similar to CSS. So the main goals are going to be:
  • Have a syntax that looks almost like CSS
  • Be able to re-use code (something CSS should really have anyways)
    • Through variables
    • Through inheritance (even to the extent that you could package a set of classes in a jar and include that jar in any application)
  • For numeric values be able to perform calculations.

Handling Numeric values

I'll start off with something simple, adding units to numeric values. I looked into Groovy Categories but they seemed to be pretty limited for what I wanted and decided to add methods to the Number class using the ExpandoMetaClass.

The NumericValue class

This will be treated as a Number, the basic operators have been overloaded and it implements Comparable. The toString() method will generate CSS text.

The Unit class will be used in conjunction with Number and NumericValue

Adding methods to the Number class

Now we need to add methods to the Number class in a Bootstrap so that when you use something like 1.px a NumericValue object is created with a value of 1 and unit of px.


Using easyb we can write a scenario that tests the NumericValue class. First we will add the methods to the Number's metaClass by calling the Bootstrap then create a NumericValue of 1px and verifying that the toString() method returns the expected value.

Ive uploaded the experiment to Google Code and the sources are available at Source.

Next I'll work on a coplete CSS Declaration and Rule


  1. There are also LESS exists, and it's already have Java binding:

  2. @splix Any link to the Java binding? I only saw the ruby stuff at

  3. Hey, It's true that we should be to re-use CSS. I followed the link to find the Java binding at the LESS site, but also couldn't find it. I'll give your code a try now, 10x! :)

  4. The LESS folks have ported everything from ruby to javascript at I've been testing it out and it works pretty well. It's nice to be able to keep everything client side as well.