Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate HTML in Racket

Tags:

html

racket

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.

like image 776
Sergi Mansilla Avatar asked Feb 12 '12 21:02

Sergi Mansilla


2 Answers

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>"
like image 126
dyoo Avatar answered Nov 11 '22 03:11

dyoo


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.

like image 21
Eli Barzilay Avatar answered Nov 11 '22 04:11

Eli Barzilay