[plt-scheme] HTML library modules

From: Danny Yoo (dyoo at hkn.eecs.berkeley.edu)
Date: Fri Dec 15 00:40:28 EST 2006


On Thu, 14 Dec 2006, Tommy Nordgren wrote:

> Can someone please point me to tutorials on using the html libraries 
> included with PLT Scheme? I want to generate HTML files from templates, 
> containing HTML fragments and embedded Scheme expressions prefixed with 
> $


Hi Tommy,

You might find Section 3 here to be useful as background:

     http://www.ccs.neu.edu/home/matthias/HtDP/Extended/servlets.html

The idea is rather than represent templates as strings, we can use 
s-expressions.


I wrote a small entry on how one might generate XML:

     http://hashcollision.blogspot.com/2006/11/how-not-to-write-xml.html

The idea is that there's already a kind of templating support that we can 
use called "quasiquotation" that works on s-expressions.  Here's a quick 
and dirty example:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
> (define name "tommy")
> (define page
     `(html (head (title "testing"))
        (body
          (p "hello " ,name))))
> page
(html (head (title "testing")) (body (p "hello " "tommy")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


Quasiquotation starts with a back-quote.  Within a quasiquoted 
s-expression, we can use the ',' unquote operator to interpolate the 
values we want to push.


We can translate this s-expression into a string:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
> (require (lib "xml.ss" "xml"))
> (xexpr->string page)
"<html><head><title>testing</title></head><body><p>hello 
tommy</p></body></html>"
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


There's a guarantees that, at least, everything is well formed.  As 
another example:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
> (define (make-link ref text)
     `(a ((href ,ref)) ,text))
>
> (make-link "http://plt-scheme.org/" "<< testing >>")
(a ((href "http://plt-scheme.org/")) "<< testing >>")
>
> (xexpr->string (make-link "http://plt-scheme.org/" "<< testing >>"))
"<a href=\"http://plt-scheme.org/\">&lt;&lt; testing &gt;&gt;</a>"
>
> (xexpr->string
     `(p ,(make-link "http://google.com/" "Google")
         "is your friend!"))
"<p><a href=\"http://google.com/\">Google</a>is your friend!</p>"
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

Notice that the xexpr->string function is automatically handling entity 
quotation.  Also, note that whatever follows the ',' can be more than a 
variable binding: it's an arbitrary expression.


This is all focused on XHTMLish generation.  If you need to do HTML, you 
might be interested in the htmlprag library:

     http://planet.plt-scheme.org/300/docs/neil/htmlprag.plt/1/3/doc.txt

If you go down to "Emitting HTML", you'll see another example there.


Good luck!


Posted on the users mailing list.