Howdy

My name is Rowan Lewis, Im a web developer and standards enthusiast currently living on the Gold Coast, Australia where I work for a brilliant design and development firm known as R&B Creative Communication.

· symphony cms · xslt

Fancy sorting with XSLT

A quick guide on how to use 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 youre 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, heres 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.

Have your say

Comments can be formatted using a limited set of HTML elements;
a, code, em and strong.

Tony Arnold said

If youre not afraid to burn a little CPU and memory, Im 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:

Its dirty, and unnecessary in systems like Symphony because of the proper date formatting (YYYYMMDD), but the statement inside the select can be dynamic just one of the many, many things I love about XSLT.

Rowan Lewis said

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