[racket] Ensuring data fed to web-server/templates is textual

From: Neil Van Dyke (neil at neilvandyke.org)
Date: Tue Feb 7 19:17:37 EST 2012

Jordan Johnson wrote at 02/07/2012 06:50 PM:
> I'm using web-server/templates to generate text, and the data in variables I reference in the template include s-exps that may, in some cases, contain image% objects.  I want it to render the image%s as plain text; even just the string "<IMAGE>" or similar would be adequate.

I don't know about "web-server/templates", but if you want to do this 
translation at the last minute, rather than simply avoiding putting 
invalid values in the s-expression in the first place, another library 
will do it:

#lang racket/base

(require (planet neil/html-writing:1:0))

(define-struct some-image-thing (x))

(define (my-html-writing-filter context thing)
   (cond ((some-image-thing? thing)
          (format "<IMAGE ~S>" (some-image-thing-x thing)))
          (error 'my-html-writing-filter
                 "Don't know how to filter ~S in context ~S"

  `(html (head (title "My Title"))
         (body (@ (bgcolor "white"))
               (h1 "My Heading")
               (p "This is a paragraph.")
               (p "This is a foreign thing: " ,(make-some-image-thing 42))
               (p "This is another paragraph.")))

This writes the output:

<html><head><title>My Title</title></head><body bgcolor="white"><h1>My 
Heading</h1><p>This is a paragraph.</p><p>This is a foreign thing: 
&lt;IMAGE 42&gt;</p><p>This is another paragraph.</p></body></html>

I originally implemented that feature 7 years ago, for last-minute 
translation of URI objects -- to output URLs as relative to the URL of 
the HTML object being written, rather than absolute.


Posted on the users mailing list.