Smalltalk CSS generation
Return to home page
Comments Loading...
2004-07-23

[Spotted in David Buck - Blog > http://www.cincomsmalltalk.com/userblogs/buck/blogView?showComments=true&entry=3267905764].

So Dave's making websites with Smalltalk in the simplest possible way available to him. I think this is a great idea. In fact, I've done similar stuff using XMLMaker before. But I thought it relevant to carry on from Dave's post to introduce a new API that we have in WithStyle.

You can now build CSS objects using normal Smalltalk syntax, and at the end, get out CSS in CSS form. Lets skip ahead to the actual details:

parser := CssParser on: ''.

We have to make a CssParser because its the only one who knows how to do a 'real' printout of CSS. We could do it ourselves at a Ruleset level, but there's no point. You may need to prefix these classes with WithStyle.CssParser depending on where you're executing the code.

ruleset := Ruleset new.
parser addRuleset: ruleset.

A Ruleset is basically a bunch of criteria for matching and then a bunch of properties.

ruleset addCriteria: 'p' asCssTypeSelector.

There are a whole bunch of selector types in CSS. Child selectors (>), adjacent selectors (+), descendant selectors (space). All of these are messages you can send to add new criteria. You can also add pseudo selectors and class selectors.

ruleset addCriteria: 'myClass' asCssClassSelector.

Now lets give it some actual properties

ruleset addProperty: (property := 'color' asCssProperty).
property addValue: #blue.
ruleset addProperty: (property := 'background-color' asCssProperty).
property addValue: (ColorValue red: 0.25 green: 0.25 blue: 0.25).

Here we've added a color and background-color. One will come out as a named color, the other will be an RGB color.

ruleset addProperty: (property := 'float' asCssProperty).
property addValue: #left.
ruleset addProperty: (property := 'width' asCssProperty).
property addValue: 10 asCssEms.

Here we've added a float: left and a width of 10em's. There are many more types of things you can add and the best way to discover them is to look at the tests that come with the code, but lets wrap this up now:

parser asCssString

We get our result of:

p.myClass { color: blue; background-color: rgb(64,64,64); float: left; width: 10em }

This code will be available tonight in the latest WithStyle release, v3.1449