Intelligent String Breaking - DVWP

There are situations like we want to show only a part of a text followed by three dots or a more link, which is straight forward using substring(). But if the requirement is to not to cut the last word in half, there is some additional work involved. Here is an XSLT template to substring without breaking words.

In here StringBreak template looping over the characters in a given string and look for the last space character within the given length. Here the looping starts from the needed size of the result string, which is CharLimit index of the given text and goes towards start until, find a space character (Actually the first space character from the searching location). Once found, it gets the index of that space character and substring from start to that character.

<!-- String Break Template -->
<xsl:template name="StringBreak">
<xsl:param name="text" />
<xsl:param name="count" />

<xsl:if test="string-length($text) &lt;= $count" >
<xsl:value-of select="$text"/>
<xsl:if test="string-length($text) &gt; $count" >
<xsl:if test="not($count &lt; 1)">
<xsl:when test="substring($text, $count + 1, 1) = ' '">
<xsl:value-of select="substring($text, 1, $count)"/> ...
<xsl:call-template name="StringBreak">
<xsl:with-param name="count" select="$count - 1" />
<xsl:with-param name="text" select="$text" />

<!--Define a variable called ‘CharLimit’, which is the size of the output -->
<xsl:variable name="CharLimit" select="'30'"></xsl:variable>

<!-- Call String Break Template -->
<xsl:call-template name="StringBreak">
<xsl:with-param name="text" select="@Title" />
<xsl:with-param name="count" select="$CharLimit" />