Wednesday, March 16, 2011

XSLT Trim String to Word Boundary with Ellipsis

I found pieces of this and modified it for my use. Include these two templates and call summary-text.



  <xsl:template name="summary-text">
    <xsl:param name="in" />
    <xsl:param name="allowable-length" select="50" />
    <xsl:if test="string-length($in) <= $allowable-length">
      <xsl:value-of select="$in" />
    xsl:if>
    <xsl:if test="string-length($in) > $allowable-length">
      <xsl:call-template name="trim-last-word">
        <xsl:with-param name="in" select="substring($in, 1, $allowable-length)" />
      xsl:call-template>
      <xsl:text>...xsl:text>
    xsl:if>
  xsl:template>

  <xsl:template name="trim-last-word">
    <xsl:param name="in" />
    <xsl:choose>
      <xsl:when test="substring($in, string-length($in), 1)=' '">
        <xsl:value-of select="$in" />
      xsl:when>
      <xsl:otherwise>
        <xsl:call-template name="trim-last-word">
          <xsl:with-param name="in" select="substring($in, 1, string-length($in)-1)" />
        xsl:call-template>
      xsl:otherwise>
    xsl:choose>
  xsl:template>


It will take a string like this:
Now is the time for all good people to come to the aid of their country.
And transform it to this:
Now is the time for all good people to come to the...

No comments:

Post a Comment