tags:

views:

201

answers:

2

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
Hey hank, why do you think xsl sort is horribly broken?
Alexander Bobin
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
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
+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 &gt;= substring-before($dateRange, ',')
        and
        $currentDate &lt; 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