HTML templating in Scheme?

Templating is one of those must-haves for building websites; separating content from presentation is sliced bread compared to cavalierly interleave logic and HTML into one file. In Scheme, I think that quasiquotation could be used in wonderful ways to create templates; namely, every template can be a function that simply takes parameters and directly uses quasiquotation as the templater:

[clojure]
(define blog-post-template
(lambda (title date message comments)
`(html
(head (title "My Blog – " ,title))
(body
(div (@ (class "post"))
(h1 ,title)
,message)
(div (@ (class "comments"))
(p ,comments) …)))))
[/clojure]

and then to use it, you would just use

[clojure]
(blog-post-template
"Another pedantic blog post"
"Nov 20, 2010"
"Today I’m going to complain about everything …"
‘("Awesome blog!"
"Actually, I disagree with you on everything"
"Spam"))
[/clojure]

You could also add a little more flexibility into your template by accepting an association list of parameters rather than fixed parameters:

[clojure]
(define blog-post-template
(lambda params
`(html
(head (title "My Blog – " ,(cadr (assq ‘title params))))
(body))))
[/clojure]

which can be made easier to use by redefining quasiquote with some templating-specific conveniences.

Leave a Reply