Messing with XSLT in SpringCMS
Wednesday, December 21, 2005I've been messing about with XSLT again. I wanted to generate the tag list you can see over there on the right. But since I'm only a beginner in XSLT I had no idea how to go about pulling out the unique entries in a list.
The heart of the SpringCMS template system is XSLT. Basically Spring offers several XML services for pulling out your data as XML which you can then transform any way you like. Each blog entry has multiple tags so what I needed to do was grab the XML for all the tags and then pull out the unique tags and count how many times each one was used.
I then discovered the incredible Dr Jeni Tennison and her death defying XSLT Pages. Bookmark this one right now. There's a wealth of knowledge there about XSLT techniques for common situations. Wouldn't you know it, there 's a whole section on 'grouping'.
So armed with Dr Jeni's XSLT Page I created this:
<xsl:key name="tags" match="category" use="."/>
<xsl:template match="/datapackets">
<div class="infobox" id="site-tags">
<h2>All Tags</h2>
<ul>
<xsl:for-each select="category[count(. | key('tags', .)[1]) = 1]">
<xsl:sort order="descending" data-type="number" select="count(key('tags', .))"/>
<xsl:if test="string(.)">
<li>
<a rel="tag">
<xsl:attribute name="href">
<xsl:text>/view/tags/query/tag/</xsl:text><xsl:value-of select="."/><xsl:text>/</xsl:text>
</xsl:attribute>
<xsl:value-of select="."/>
</a> (<xsl:value-of select="count(key('tags', .))"/>)
</li>
</xsl:if>
</xsl:for-each>
</ul>
</div>
</xsl:template>
It's a fiendishly clever use of the key tag called the " Muenchian Method" after the creator Steve Muench. What it does is this:
- Register a key for each category element using the value of the element as the key
- Then it loops on unique category values. A unique value is one where the nodeset of the union of a category and the first category node of all categories with the same key contains only one node. In plain english this means it's the first of every category duplicate.
- Then count the number of category elements with the same key.
Easy!
And what is really awsome is the way SpringCMS makes it available for me in a simple 'feed' url:
http://tetlaw.id.au/feed/format/tetlaw.blog.tags/limit/10000
Cool huh?
No comments yet