Monday, March 8, 2010

Working with CGI: Part 4

In parts 1, 2, and 3, we learned about parsing CGI requests using Factor.

I wanted to take a moment and talk about using templates to develop web sites. Many web developers will suggest that using templates is a good way to separate presentation and content, making it easier for teams to work together to build a website, as well as other benefits.

There is no magic to most template systems. Fundamentally, these systems take some text (usually in a hybrid "template language"), compile it into code, using the compiled template to output a dynamic page.

In Factor, the html.templates vocabulary allows access to several HTML template implementations including Chloe and FHTML. Some differences between the two include:

  • requiring XML (Chloe) or HTML (FHTML)
  • embedding data (Chloe) or Factor code (FHTML)

Depending on your use-case, you might have a preference for one versus the other. If neither suite your purpose, you could even implement your own with a modest amount of work.

Embedding a template into a Factor CGI script is pretty easy. Here is an example of using the FHTML vocabulary to parse a template and then call it to render a page.

#! /path/to/factor

USE: io

"Content-type: text/html\n\n" print

USE: html.templates.fhtml

<% USING: calendar formatting math math.parser io ; %>

    <head><title>Simple Embedded Factor Example</title></head>
        The time is <% now "%c" strftime write %>
        <% 5 [ %><p>I like repetition</p><% ] times %>

""" parse-template call( -- )

When run from Factor, or accessed as a CGI script, this will print a page something like the following:

The time is Mon Mar 08 23:12:47 2010.

I like repetition

I like repetition

I like repetition

I like repetition

I like repetition

Many large web applications are built with some kind of template engine, frequently using smart caching of compiled templates for performance, and usually storing the template files separately from the CGI script that loads and calls them.

But, it all basically starts with this.

No comments: