Computed Pages

The Demo Page created in the Generating HTML lesson could have been created by a static file served by a conventional Web server, such as Apache. And in fact CL-HTTP can serve static files too.

But CL-HTTP really comes into its own when you want to create dynamic, interactive Web pages whose content changes.

The next example gives a light-hearted example illustrating how this works.

First we create a couple of routines to help. The first one, random-elt, returns a random element of a list:

(defun random-elt (list) (elt list (random (length list))))

Using this we define a random-aphorism program:

(defun aphorism (stream)
  "Write a random aphorism to stream."
  (format stream "~a ~a."
           '("Many hands make" "Too many cooks spoil" "A stitch in time saves"
             "All work and no play makes" "Money is"))
           '("light work" "the broth" "nine" "Jack a dull boy" "the root of all evil"))))

Here's the routine to create the page:

(defun write-aphorism (url stream)
  "Display a random aphorism."
  (with-page (url stream "Aphorism of the Day")
    (with-paragraph (:stream stream)
      (aphorism stream))))

Finally, we export the URL using export-url:

(export-url "http://localhost:8000/aphorism.html"
            :response-function 'write-aphorism)

Each time we access the page a new aphorism is generated:


blog comments powered by Disqus