forked from hannonhill/XSLT-Workbook
/
truncate-string-by-words.xsl
54 lines (48 loc) · 1.51 KB
/
truncate-string-by-words.xsl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<!--
Truncate String at Word Boundary
Created by Ross Williams on 2010-04-20.
USAGE
_____
In any XSLT Format:
/BEGIN EXAMPLE/
<xsl:stylesheet ...>
...
<xsl:include href="Path_To_truncate-string-by-words_XSLT_Format_Asset" />
...
<xsl:template match="system-page">
... OTHER INFO ABOUT PAGE ...
<h2>
<xsl:call-template name="truncate-at-word">
<xsl:with-param name="length" select="50" />
<xsl:with-param name="string" select="title" />
</xsl:call-template>
</h2>
...
</xsl:template>
</xsl:stylesheet>
/END EXAMPLE/
-->
<xsl:stylesheet version="1.0" xmlns:str="http://exslt.org/strings" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template name="truncate-at-word">
<xsl:param name="length" select="140"/>
<xsl:param name="string"/>
<xsl:param name="tokens" select="'	

 '" />
<xsl:variable name="max" select="number($length)"/>
<xsl:variable name="stringLength" select="string-length($string)" />
<xsl:variable name="roughCut" select="substring($string, 1, $max)"/>
<xsl:variable name="tokenized" select="str:tokenize($roughCut, $tokens)"/>
<xsl:choose>
<xsl:when test="$stringLength > $max">
<xsl:for-each select="$tokenized[position() < last()]">
<xsl:value-of select="."/>
<xsl:if test="position() != last()">
<xsl:text> </xsl:text>
</xsl:if>
</xsl:for-each>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$string"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>