XSLT for HTML templating engine

General Development

Easy description of how and why to use XSLT as your template engine.

Date : 2007-06-26
It seems like XML is taking over the world. We're using it in our databases, web services, even our HTML is slowly turning into correct XML. With all of this I still see a lot of string based HTML templating engines. I've even written an article about how you could build your own string based HTML templates.

Recently, though, I've become acquainted with using XSL and XML together to create beautiful, reusable, standard compliant templates. I inherited a web site that had almost all of it's pages output with XSL templates and besides the occasional issue that creating correct XML can bring up I've found it to be the best templating engine I've ever used. In my spare time, of which I have very little, I'm working on a Site Structure that is based on this method (like a CMS, but for programmers not content developers). The Site Structure will provide the data via XML and the XSL template will be used to display it.

One of the many great things about this method is that almost every language has access to XSLT. Using this logic and a well created database one could create a site and deploy it on any of the major platforms such as LAMP, WISA, WISP, or WIMP. There would just need to be a standard XML structure to create from each dataset. Modules could be created for the site and added on simply by adding a node to the XML structure, or modifying an existing node. Then the templates could be adapted to handle this data how the user saw fit.

The basic concept is to create an XML object with all your dynamic data and transform it with your XSLT template. This results in correctly formatted HTML output. The code to transform XML with XSL is simple in any language but the example below shows how to pass either XML and XSL strings or an XML object and the filename of the XSL to a function that will then gather the XML and XSL and transform it either outputting the results immediately or returning them for further processing.

Just to give an idea of how XSLT can easily be used to transform dynamic data into HTML take a look at the sample XML, XSL and ASP below:

  Option Explicit
  Response.ContentType = "text/html; charset=UTF-8"

  Dim objXml

  set objXml = Server.CreateObject("Msxml2.DOMDocument")
  objXml.Load Server.MapPath("data.xml")

  Call TransformXml("page.xsl", objXml, true, true, true)

Function TransformXml(strPageTemplate, varXml, blnXslFile, blnXmlObj, blnWrite)
  Dim objSourceXsl, objSourceXml
  Set objSourceXml = Server.CreateObject("Msxml2.DOMDocument")
  Set objSourceXsl = Server.CreateObject("Msxml2.DOMDocument")
  objSourceXml.async = False : objSourceXsl.async = False

  If blnXmlObj Then Set objSourceXml = varXml Else objSourceXml.LoadXml varXml
  If blnXslFile Then objSourceXsl.Load Server.MapPath(strPageTemplate) Else objSourceXsl.LoadXml strPageTemplate
  If blnWrite Then
    Response.Write objSourceXml.TransformNode(objSourceXsl)
    Set TransformXml = objSourceXml.TransformNode(objSourceXsl)
  End If
  Set objSourceXml = Nothing
  Set objSourceXsl = Nothing
End Function

Oh, ok, I'll give it to you in PHP5 as well:
$xsl = new DomDocument();
$inputdom = new DomDocument();

/* create the processor and import the stylesheet */
$proc = new XSLTProcessor();
$xsl = $proc->importStylesheet($xsl);

/* transform and output the xml document */
$newdom = $proc->transformToDoc($inputdom);
print $newdom->saveXML();

Notably we are skipping the database interaction and pulling our XML straight from a file on the disk. The XML we're using is this:

  <title>Test Page</title>
  <keywords>test, xml, xsl</keywords>
    this is a test page to show how to use XSL templates as the templating engine for your dynamic HTML pages</description>
  <pageheading>Test Page</pageheading>
      <title>Home Page</title>
      <title>Business Site</title>
      <display>BeachBum Software</display>
    This is the main content of the page.  <b>you can include Html</b> tags in this content area and have them displayed <u>correctly</u>

This is a very basic example but it shows a few of the basic concepts of how raw XML data can be converted into standards compliant HTML.

Now for the XSL. There are many XSL tutorials online so I'm not going to try to rewrite any of them. If you are unfamiliar with the XSL structure do a Google search for XSL and you'll find more than you need. Below you will see some of the basic concepts necessary to convert XML data into the format that you want.

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/d">
    <title><xsl:value-of select="title"/></title>
    <xsl:element name="meta">
      <xsl:attribute name="name">keywords</xsl:attribute>
      <xsl:attribute name="content"><xsl:value-of select="keywords"/></xsl:attribute>
    <xsl:element name="meta">
      <xsl:attribute name="name">description</xsl:attribute>
      <xsl:attribute name="content"><xsl:value-of select="description"/></xsl:attribute>
    <link href="style.css" rel="stylesheet" type="text/css" />
    <div id="page">
      <div id="header"><xsl:value-of select="pageheading"/></div>
      <div id="leftnav">
        <ul id="leftnavlist">
          <xsl:for-each select="navigation/leftnav">
            <xsl:sort select="display" order="descending"/>
              <xsl:element name="a">
                <xsl:attribute name="href"><xsl:value-of select="href"/></xsl:attribute>
                <xsl:attribute name="target"><xsl:value-of select="target"/></xsl:attribute>
                <xsl:attribute name="title"><xsl:value-of select="title"/></xsl:attribute>
                <xsl:value-of select="display"/>
      <div id="content">
        <xsl:copy-of select="content"/>

It would probably be a good idea to separate the basic page template and the more dynamic content area into 2 XSL templates, but it is not necessary as this example shows. Notice the simplest way to pull data values from the XML is using the XSL element xsl:value-of select=”XPATH”. That doesn't work for HTML content though so when you go to pull HTML into a section you use xsl:copy-of select=”XPATH”

This example should get you on your way to using XSLT as your HTML templating engine. You will find many benefits to this including speed of delivery, cross platform compatibility, and save you the time of creating or learning another templating language.

You can see what the output of this looks like here: XSLT Template Example ASP
XSLT Template Example PHP

Comments :

No comments yet
  • Search For Articles