Incrementing and logic in XSL

17 11 2009

I’ve been learning XSL for the design of the learning guide I mentioned in my last post. I just had a bit of a win with incrementing in the XSL! I searched the net far and wide and didn’t find anything that suited what I wanted in terms of incrementing, most things didn’t even work anyway.

The XML I’m transforming describes the content in terms of “sections”. The XSL transforms those sections into a jquery tabbed interface. So basically, I need the title attributes of the tab links, to match the id attributes of the div containers. I also need these to be unique for the jquery tabs to work. Thus, I wanted to increment the values.

Here’s a sample of the XML, just a simple example – an item is a module in the learning guide, it contains various information, part of which includes the actual ‘content’ for that module:

<itemContent>
<section title="Start">
<sectionContent>first section of this module</sectionContent>
</section>
<section title="Middle one">
<sectionContent>content for middle section</sectionContent>
</section>
<section title="Finish">
<sectionContent>content for third section here</sectionContent>
</section>
</itemContent>

Then, the XSL that transforms and increments. I had it all around the wrong way initially, I was trying to use variables and addition, loops etc, to do my incrementing.. but really, all I had to do was identify the node position and use that as a parameter in my for-each loop!

<div id="tabs">
	<xsl:for-each select="itemContent/section">                    
		<xsl:param name="i"><xsl:number value="position()" /></xsl:param>
		<a href="#" title="Section_{$i}"><xsl:value-of select="@title" /></a>              		
	</xsl:for-each>
	<div class="clear"></div>
</div>

<xsl:for-each select="itemContent/section">
	<xsl:param name="i"><xsl:number value="position()" /></xsl:param>
	<div id="Section_{$i}" class="hiddencontent">
		<h3><xsl:value-of select="@title" /></h3>
		<xsl:copy-of select="sectionContent" />
	</div>
</xsl:for-each>

It works a charm and it renders like this in the browser:

HTML render of the XSL incrementing

Note the incrementing and matching title/id attributes..

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: