What would be the recommended way to generate HTML from X-expressions in Racket? Looks like response/xexpr
would do it, but seems to be designed for serving http responses. The only thing I need is to generate an HTML string from Racket lists (or X-expressions), no need to have a web server involved.
The xexpr->string function in the xml
library should do what you're asking, if I'm not mistaken. For an example where it's used, you can take a look here, where the example uses it to generate HTML responses for a simplified web server application.
> (xexpr->string '(html (head (title "Hello")) (body "Hi!")))
"<html><head><title>Hello</title></head><body>Hi!</body></html>"
If you're willing to dump xexprs for a potentially more convenient facility, then there is a new language which is used to generate the Racket web pages. It's not yet documented (therefore it is still new and not properly public), but you can see how it's used in these sources. As a quick example that demonstrates it, run this:
#lang scribble/html
@(define name "foo")
@html{@head{@title{@name}}
@body{@h1{@name}}}
Another example uses it as a library:
#lang at-exp racket/base
(require scribble/html)
(define (page name)
(output-xml
@html{@head{@title{@name}}
@body{@h1{@name}}}))
@page{foo}
The at-exp
is not needed, it just makes it easy to write lots of text in code. (And it would be just as useful with xexprs too.)
The main difference is that in this language the HTML tags are actually bindings, which makes it convenient to maintain code. It's also very flexible in what it can take as texts -- for example, there is no need to keep it to a strict list of strings and sub-tags, so you never face questions like where to use append-map
etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With