Building-blocks logo. Incremental Development, Inc.

XSL example, XSLT example, XSL sample, XSLT sample, XSL tutorial, XSLT tutorial, stupid XSL trick, stupid XSLT trick.

Joel Aufgang's Wing of the Gallery of Stupid XSL and XSLT Tricks

This page is Joel Aufgang's wing of the Gallery of Stupid XSL and XSLT Tricks.

Fractal

This trick will generate a fractal Sierpinsky triangle using recursive template calls. You can set the depth, color and size of the fractal.

Be careful about setting depth above 8 or 9... it takes a long time to render and gobbles up memory.

Input

Here is a sample input file. Name it fractal.xml and open it with IE6:

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="fractal.xsl"?>
<fractal depth="5" color="blue" size="1"/>

Stylesheet

Here is the stylesheet that creates the fractal (name it fractal.xsl, in same folder as the input file):

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="fractal">
    <xsl:param name="depth" select="@depth"/>
    <table border="0" cellpadding="0" cellspacing="0">
      <tr>
        <td>
          <xsl:call-template name="iterate">
            <xsl:with-param name="depth" select="$depth"/>
          </xsl:call-template>
        </td>
      </tr>
      <tr>
        <td>
          <xsl:call-template name="iterate">
            <xsl:with-param name="depth" select="$depth"/>
          </xsl:call-template>
        </td>
        <td>
          <xsl:call-template name="iterate">
            <xsl:with-param name="depth" select="$depth"/>
          </xsl:call-template>
        </td>
      </tr>
    </table>
  </xsl:template>

  <xsl:template name="iterate">
    <xsl:param name="depth"/>
    <xsl:choose>
      <xsl:when test="$depth &gt; 0">
        <xsl:apply-templates select=".">
          <xsl:with-param name="depth" select="$depth+(-1)"/>
        </xsl:apply-templates>
      </xsl:when>
      <xsl:otherwise>
        <table cellpadding="0" cellspacing="0" border="0" height="{@size}" width="{@size}">
          <tr><td bgcolor="{@color}"></td></tr>
        </table>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

</xsl:stylesheet>

Output

Output appears as below in your browser: