On this page:
7.1 Static
7.2 Dynamic
7.3 Gotchas
7.4 HTTP Responses
7.5 API Details
include-template
in
7.6 Conversion Example

7 Templates: Separation of View

 (require web-server/templates)

The Web Server provides a powerful Web template system for separating the presentation logic of a Web application and enabling non-programmers to contribute to Racket-based Web applications.

Although all the examples here generate HTML, the template language and the Text Preprocessing it is based on can be used to generate any text-based format: C, SQL, form emails, reports, etc.

7.1 Static

Suppose we have a file "static.html" with the contents:

  <html>

   <head><title>Fastest Templates in the West!</title></head>

   <body>

    <h1>Bang!</h1>

    <h2>Bang!</h2>

   </body>

  </html>

If we write the following in our code:
  (include-template "static.html")

Then the contents of "static.html" will be read at compile time and compiled into a racket program that returns the contents of "static.html" as a string:
  "<html>\n  <head><title>Fastest Templates in the West!</title></head>\n  <body>\n    <h1>Bang!</h1>\n    <h2>Bang!</h2>\n  </body>\n</html>"

7.2 Dynamic

include-template gives the template access to the complete lexical context of the including program. This context can be accessed via the @ Syntax syntax. For example, if "simple.html" contains:

  <html>

   <head><title>Fastest @thing in the West!</title></head>

   <body>

    <h1>Bang!</h1>

    <h2>Bang!</h2>

   </body>

  </html>

Then
  (let ([thing "Templates"])
    (include-template "simple.html"))
evaluates to the same content as the static example.

There are no constraints on how the lexical context of the template is populated. For instance, you can built template abstractions by wrapping the inclusion of a template in a function:
  (define (fast-template thing)
    (include-template "simple.html"))
  
  (fast-template "Templates")
  (fast-template "Noodles")
evalutes to two strings with the predictable contents:

  <html>

   <head><title>Fastest Templates in the West!</title></head>

   <body>

    <h1>Bang!</h1>

    <h2>Bang!</h2>

   </body>

  </html>

and

  <html>

   <head><title>Fastest Noodles in the West!</title></head>

   <body>

    <h1>Bang!</h1>

    <h2>Bang!</h2>

   </body>

  </html>

Furthermore, there are no constraints on the Racket used by templates: they can use macros, structs, continuation marks, threads, etc. However, Racket values that are ultimately returned must be printable by the Text Preprocessing. For example, consider the following outputs of the title line of different calls to fast-template:

7.3 Gotchas

To obtain an @ character in template output, you must escape the it, because it is the escape character of the @ Syntax syntax. For example, to obtain:

  <head><title>Fastest @s in the West!</title></head>

You must write:

  <head><title>Fastest @"@"s in the West!</title></head>

as your template: literal @s must be replaced with @"@". (Note that the double-quotes are basically a Racket expression, which can be used for longer strings too.)

The @ Syntax will read Racket identifiers, so it does not terminate identifiers on punctuations or XML angle brackets. So,

  <head><title>Fastest @thing in the @place!</title></head>

will complain that the identifier place!</title></head> is undefined. You can subvert this by explicitly delimiting the identifer:

  <head><title>Fastest @thing in the @|place|!</title></head>

Another gotcha is that since the template is compiled into a Racket program, only its results will be printed. For example, suppose we have the template:

  <table>

   @for[([c clients])]{

    <tr><td>@(car c), @(cdr c)</td></tr>

   }

  </table>

If this is included in a lexical context with clients bound to
  (list (cons "Young" "Brigham") (cons "Smith" "Joseph"))
then the template will be printed as:

  <table>

  </table>

because for does not return the value of the body. Suppose that we change the template to use for/list (which combines them into a list):

  <table>

   @for/list[([c clients])]{

    <tr><td>@(car c), @(cdr c)</td></tr>

   }

  </table>

Now the result is:

  <table>

   </tr>

   </tr>

  </table>

because only the final expression of the body of the for/list is included in the result. We can capture all the sub-expressions by using list in the body:

  <table>

   @for/list[([c clients])]{

    @list{

     <tr><td>@(car c), @(cdr c)</td></tr>

    }

   }

  </table>

Now the result is:

  <table>

   <tr><td>Young, Brigham</td></tr>

   <tr><td>Smith, Joseph</td></tr>

  </table>

The templating library provides a syntactic form to deal with this issue for you called in:

  <table>

   @in[c clients]{

    <tr><td>@(car c), @(cdr c)</td></tr>

   }

  </table>

Notice how it also avoids the absurd amount of punctuation on line two.

7.4 HTTP Responses

The quickest way to generate an HTTP response from a template is using a response? struct:
  (response/full
   200 #"Okay"
   (current-seconds) TEXT/HTML-MIME-TYPE
   empty
   (list (string->bytes/utf-8 (include-template "static.html"))))

Finally, if you want to include the contents of a template inside a larger X-expression :
  `(html ,(include-template "static.html"))
will result in the literal string being included (and entity-escaped). If you actually want the template to be unescaped, then create a cdata structure:
  `(html ,(make-cdata #f #f (include-template "static.html")))

7.5 API Details

Compiles the template at path using the @ Syntax syntax within the enclosing lexical context.

Example:
  (include-template "static.html")

(in x xs e ...)
Expands into
  (for/list ([x xs])
   (begin/text e ...))

Template Example:

  @in[c clients]{

   <tr><td>@(car c), @(cdr c)</td></tr>

  }

Racket Example:
  (in c clients "<tr><td>" (car c) ", " (cdr c) "</td></tr>")

7.6 Conversion Example

Al Church has been maintaining a blog with Racket for some years and would like to convert to web-server/templates.

The data-structures he uses are defined as:
  (define-struct post (title body))
  
  (define posts
    (list
     (make-post
      "(Y Y) Works: The Why of Y"
      "Why is Y, that is the question.")
     (make-post
      "Church and the States"
      "As you may know, I grew up in DC, not technically a state.")))
Actually, Al Church-encodes these posts, but for explanatory reasons, we’ll use structs.

He has divided his code into presentation functions and logic functions. We’ll look at the presentation functions first.

The first presentation function defines the common layout of all pages.
  (define (template section body)
    (response/xexpr
     `(html
       (head (title "Al's Church: " ,section))
       (body
        (h1 "Al's Church: " ,section)
        (div ([id "main"])
             ,@body)))))

One of the things to notice here is the unquote-splicing on the body argument. This indicates that the body is list of X-expressions. If he had accidentally used only unquote then there would be an error in converting the return value to an HTTP response.

  (define (blog-posted title body k-url)
    `((h2 ,title)
      (p ,body)
      (h1 (a ([href ,k-url]) "Continue"))))

Here’s an example of simple body that uses a list of X-expressions to show the newly posted blog entry, before continuing to redisplay the main page. Let’s look at a more complicated body:

  (define (blog-posts k-url)
    (append
     (apply append
            (for/list ([p posts])
              `((h2 ,(post-title p))
                (p ,(post-body p)))))
     `((h1 "New Post")
       (form ([action ,k-url])
             (input ([name "title"]))
             (input ([name "body"]))
             (input ([type "submit"]))))))

This function shows a number of common patterns that are required by X-expressions. First, append is used to combine different X-expression lists. Second, apply append is used to collapse and combine the results of a for/list where each iteration results in a list of X-expressions. We’ll see that these patterns are unnecessary with templates. Another annoying patterns shows up when Al tries to add CSS styling and some JavaScript from Google Analytics to all the pages of his blog. He changes the template function to:

  (define (template section body)
    (response/xexpr
     `(html
       (head
        (title "Al's Church: " ,section)
        (style ([type "text/css"])
               "body {margin: 0px; padding: 10px;}"
               "#main {background: #dddddd;}"))
       (body
        (script
         ([type "text/javascript"])
         ,(make-cdata
           #f #f
           "var gaJsHost = ((\"https:\" =="
           "document.location.protocol)"
           "? \"https://ssl.\" : \"http://www.\");"
           "document.write(unescape(\"%3Cscript src='\" + gaJsHost"
           "+ \"google-analytics.com/ga.js' "
           "type='text/javascript'%3E%3C/script%3E\"));"))
        (script
         ([type "text/javascript"])
         ,(make-cdata
           #f #f
           "var pageTracker = _gat._getTracker(\"UA-YYYYYYY-Y\");"
           "pageTracker._trackPageview();"))
        (h1 "Al's Church: " ,section)
        (div ([id "main"])
             ,@body)))))

Some of these problems go away by using here strings, as described in the documentation on Reading Strings.

The first thing we notice is that encoding CSS as a string is rather primitive. Encoding JavaScript with strings is even worse for two reasons: first, we are more likely to need to manually escape characters such as "; second, we need to use a CDATA object, because most JavaScript code uses characters that "need" to be escaped in XML, such as &, but most browsers will fail if these characters are entity-encoded. These are all problems that go away with templates.

Before moving to templates, let’s look at the logic functions:
  (define (extract-post req)
    (define binds
      (request-bindings req))
    (define title
      (extract-binding/single 'title binds))
    (define body
      (extract-binding/single 'body binds))
    (set! posts
          (list* (make-post title body)
                 posts))
    (send/suspend
     (lambda (k-url)
       (template "Posted" (blog-posted title body k-url))))
    (display-posts))
  
  (define (display-posts)
    (extract-post
     (send/suspend
      (lambda (k-url)
        (template "Posts" (blog-posts k-url))))))
  
  (define (start req)
    (display-posts))

To use templates, we need only change template, blog-posted, and blog-posts:

  (define (template section body)
    (response/full
     200 #"Okay"
     (current-seconds) TEXT/HTML-MIME-TYPE
     empty
     (list (string->bytes/utf-8 (include-template "blog.html")))))
  
  (define (blog-posted title body k-url)
    (include-template "blog-posted.html"))
  
  (define (blog-posts k-url)
    (include-template "blog-posts.html"))

Each of the templates are given below:

"blog.html":

  <html>

   <head>

    <title>Al's Church: @|section|</title>

    <style type="text/css">

     body {

      margin: 0px;

      padding: 10px;

     }

  

     #main {

      background: #dddddd;

     }

    </style>

   </head>

   <body>

    <script type="text/javascript">

     var gaJsHost = (("https:" == document.location.protocol) ?

       "https://ssl." : "http://www.");

     document.write(unescape("%3Cscript src='" + gaJsHost +

       "google-analytics.com/ga.js'

        type='text/javascript'%3E%3C/script%3E"));

    </script>

    <script type="text/javascript">

     var pageTracker = _gat._getTracker("UA-YYYYYYY-Y");

     pageTracker._trackPageview();

    </script>

  

    <h1>Al's Church: @|section|</h1>

    <div id="main">

      @body

    </div>

   </body>

  </html>

Notice that this part of the presentation is much simpler, because the CSS and JavaScript can be included verbatim, without resorting to any special escape-escaping patterns. Similarly, since the body is represented as a string, there is no need to remember if splicing is necessary.

"blog-posted.html":

  <h2>@|title|</h2>

  <p>@|body|</p>

  

  <h1><a href="@|k-url|">Continue</a></h1>

"blog-posts.html":

  @in[p posts]{

   <h2>@(post-title p)</h2>

   <p>@(post-body p)</p>

  }

  

  <h1>New Post</h1>

  <form action="@|k-url|">

   <input name="title" />

   <input name="body" />

   <input type="submit" />

  </form>

Compare this template with the original presentation function: there is no need to worry about managing how lists are nested: the defaults just work.