Add variable support to CSS with Emacs and Perl/Template::Toolkit
It's very frustrating that we always have to repeat ourselves to write CSS because it hasn't supported variables for a long time. And so, people hacked the problem in various way, for example, CSS Server-side Constants. That's pretty cool way to do that, but can't we make it more simply?
Of course, we can ;)
Here's the strategy to do that:
- Use freely customizable editor: Vim, Emacs, etc.
- Utilize existing templating systems like ERb (Ruby), Template::Toolkit(Perl), Smarty (PHP), etc to write a template and to have CSS support variables artificially
- Customize the editor to automatically generate a sheer CSS file from the template when we save it
- Then we'll get a ordinary CSS file without server-side processing and any special configurarions
secondlife-san demonstrated it with Vim and Ruby/ERb. It's really easy way and highly expressive due to ERb, Ruby's standard templating system. How cool it is!
But I'm not familiar with both Vim and Ruby/ERb at all, so I tried with Emacs and Perl/Template::Toolkit, and show you how to do that with them below.
First, add the following code snippet into your .emacs file. When you edit and save a template for CSS or others, Emacs automatically generates another file based on its name using "tpage", an adjunct utility to TT.
(add-hook 'after-save-hook
(lambda ()
(if (string-match "\\(.+\\)\\.tpage\\.\\(.+\\)" (buffer-file-name))
(save-excursion
(setq filename (concat (match-string 1 buffer-file-name) "." (match-string 2 buffer-file-name)))
(shell-command
(format (concat "tpage %s > %s && echo Compiled " filename) (buffer-file-name) filename))))))
Second, write a template on TT syntax with Emacs, and save it as like "(filename).tpage.(extension)", for example, "demo.tpage.css".
[%
red = "#FF3333"
line = "3px solid ${red}"
-%]
p {
color: [% red %];
border: [% line %];
}
Then you'll see a file generated automatically and named "demo.css", and it'll contain the following sinippet of CSS code.
p {
color: #FF3333;
border: 3px solid #FF3333;
}
The way described above has more potential than I demonstrated. Actually, secondlife also demonstrated to generate a YAML file with some embedded ruby code. Needless to say, TT also can do that as well. It's your turn to hack more, enjoy!
