I am using an xslt transform to show a long list of events. It has paging, but what I would like is for it to default to the first events that are closest to the current date.
A:
Since sorting in XSLT 1.0 is horribly, horribly broken, your best bet is to find an extension or include a Unix-style time somewhere in your source XML so you can sort on that (although an ISO-formatted string might also work).
Hank Gay
2009-12-23 14:42:18
Hey hank, why do you think xsl sort is horribly broken?
Alexander Bobin
2009-12-23 14:49:23
Because it can't sort anything that's not a string or number. Instead, you have to hack a string representation that sorts the way you want it to.
Hank Gay
2009-12-23 15:14:15
I am not actually looking to sort the output.It is already. In a list of n pages, I need to go to the 1st page that includes the current date in its range
Phil Speth
2009-12-31 22:54:56
+1
A:
I'm assuming you have a useful date format (YYYY-MM-DD).
<xsl:param name="currentDate" select="''" /><!-- fill this from outside! -->
<xsl:template name="isPageSelected"><!-- returns true or false -->
<xsl:param name="eventsOnPage" /><!-- expects a node-set of events -->
<xsl:choose>
<xsl:when test="$eventsOnPage">
<!-- create a string "yyyy-mm-dd,YYYY-MM-DD-" (note the trailing dash) -->
<xsl:variable name="dateRange">
<xsl:for-each select="$eventsOnPage">
<xsl:sort select="date" />
<xsl:if test="position() = 1">
<xsl:value-of select="concat(date, ',')" />
</xsl:if>
<xsl:if test="position() = last()">
<xsl:value-of select="concat(date, '-')" />
</xsl:if>
</xsl:for-each>
</xsl:variable>
<!-- trailing dash ensures that the "less than" comparison succeeds -->
<xsl:value-of select="
$currentDate >= substring-before($dateRange, ',')
and
$currentDate < substring-after($dateRange, ',')
" />
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="false()" />
</xsl:otherwise>
</xsl:choose>
</xsl:template>
So in your paging routine, to find out if the current page is the selected one, invoke
<xsl:variable name="isPageSelected">
<xsl:call-template name="isPageSelected">
<xsl:with-param name="eventsOnPage" select="event[whatever]" />
</xsl:call-template>
</xsl:variable>
<!-- $isPageSelected now is true or false, proceed accordingly -->
Tomalak
2010-03-05 10:55:11