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:

(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) ...)))))

and then to use it, you would just use

(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"))

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

(define blog-post-template
  (lambda params
    `(html
       (head (title "My Blog - " ,(cadr (assq 'title params))))
       (body))))

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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>