Send via SMS

Monday, February 13, 2006

Page Compiler

http://littlelanguages.com/web/languages/page2html/

Here's a little page compiler, it isn't much, but it points the way towards larger systems. I've used variations on this theme in many projects, and it works quite well, especially when used atop a version control system.

So we take a page written in an XML language which supports a superset of HTML, such as this one:

<page title="Example Page">
<ol>
  <li>Apple</li>
  <li>Banana</li>
  <li>Pear</li>
</ol>
<w page="Monkey"/>
</page>

And we write a transform which can resolve this page, expanding only the new elments we define (such as <w page="NAME"/>):

<xsl:transform version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!--
 ! This transform demonstrates how we can transform
 ! page documents which contain supersets of html
 ! into pure html.
 +-->

<xsl:template match="page">
<html>
<head>
  <title><xsl:value-of select="@title"/></title>
  </head>
<body>
  <h1><xsl:value-of select="@title"/></h1>
  <xsl:apply-templates mode="resolve-page"/>
  </body>
  </html>
  </xsl:template>

<xsl:template match="node()" mode="resolve-page">
  <!--
   ! This is an identity template in XSLT. However,
   ! other templates with higer specificity will
   ! override this where appropriate.
   +-->
  <xsl:copy>
    <xsl:for-each select="attribute::*">
      <xsl:copy/>
      </xsl:for-each>
    <xsl:apply-templates mode="resolve-page"/>
    </xsl:copy>
  </xsl:template>

<xsl:template match="w" mode="resolve-page">
  <!--
   ! Here we resolve <w page="Name"/> elements into
   ! wikipedia links.
   +-->
  <a style="cursor: help"
     href="http://en.wikipedia.org/wiki/{@page}">
    <xsl:value-of select="@page"/>
    </a>
  </xsl:template>

</xsl:transform>

Applied to our earlier example, we get (example.html):

<html>
<head>
<meta http-equiv="Content-Type"
    content="text/html; charset=UTF-8">
<title>Example Page</title>
</head>
<body>
<h1>Example Page</h1>
<ol>
  <li>Apple</li>
  <li>Banana</li>
  <li>Pear</li>
</ol>
<a style="cursor: help"
    href="http://en.wikipedia.org/wiki/Monkey"
    >Monkey</a>
</body>
</html>

Now, all we need is a script to compile all pages in our directory tree, and we can stop writting HTML boilerplate!

#!/bin/bash
STYLESHEET="$(dirname $0)/page2html.xsl"
echo -n "Compiling pages ";
find . -name '*.page.xml' | while read PAGE; do
  echo -n "." # A nice little progress message.
  PAGE_DIR=$(dirname "$PAGE");
  PAGE_BASENAME=$(basename "$PAGE" .page.xml);
  xsltproc \ 
     -o "$PAGE_DIR/$PAGE_BASENAME.html" \ 
     "$STYLESHEET" \ 
     "$PAGE";
done;
echo
exit 0

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home