Fancy sorting with XSLT

A quick guide on how to use multiple–sorting in XSLT to your advantage.

I was working on a custom page for a news site recently, the page had to list 3 news stories per category of the site, with a predefined order for some categories, with the rest following afterwards in alphabetical order.

So, perhaps you're thinking:

<xsl:template match="news-categories">
	<xsl:apply-templates select="category[@handle = 'news']" mode="list" />
	<xsl:apply-templates select="category[@handle = 'opinions']" mode="list" />
	
	<!-- And then came the mob -->
	<xsl:apply-templates select="category[
		@handle != 'news'
		and @handle != 'opinions'
	]" mode="list">
		<xsl:sort select="@handle" order="ascending" />
	</xsl:apply-templates>
</xsl:template>

Which would work, but would get kind of nasty if you need to add a third or fourth category. Instead, here's my solution:

<xsl:template match="news-categories">
	<xsl:apply-templates select="category" mode="list">
		<xsl:sort select="@handle = 'news'" order="descending" />
		<xsl:sort select="@handle = 'opinions'" order="descending" />
		
		<!-- And then came the mob -->
		<xsl:sort select="@handle" order="ascending" />
	</xsl:apply-templates>
</xsl:template>

Neat huh? It forces the categories you need to the top of the list, satisfying the clients whim without them even knowing.

Share your thoughts...

Tony Arnold wrote on :

If you're not afraid to burn a little CPU and memory, I'm a big fan of saving myself time when sorting by non standard date formats and using a substring() call inside the xsl:sort's select attribute:

<xsl:sort select="substring(date-published, 1, 4)" order="descending"/>
<xsl:sort select="substring(date-published, 6, 2)" order="descending"/>

It's dirty, and unnecessary in systems like Symphony because of the proper date formatting (YYYY–MM–DD), but the statement inside the select can be dynamic – just one of the many, many things I love about XSLT.

Rowan Lewis wrote on :

I've done something similar by using translate() to remove the hyphens or slashes in date string.

Martin Janiczek wrote on :

Hah, I ended up using Order Entries extension because of that. You can add new “order” field to your sections and then fiddle with it in administration… and sort by it on the frontend and what not.