Created
February 20, 2009 16:06
-
-
Save neilalbrock/67529 to your computer and use it in GitHub Desktop.
Another take on the tolerant truncate utility.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> | |
<!-- | |
Author: Neil Albrock | |
Version: 1.0 | |
Description: Truncate by a character limit and retain HTML content. | |
Usage: | |
<xsl:call-template name="truncate"> | |
<xsl:with-param name="data" select="path/to/your/body" /> | |
<xsl:with-param name="length" select="250" /> | |
<xsl:with-param name="link" select="'href'" /> | |
</xsl:call-template> | |
--> | |
<xsl:template name="truncate"> | |
<!-- The node set to be worked on. --> | |
<xsl:param name="data"/> | |
<!-- The desired truncate length. Default to length of data. --> | |
<xsl:param name="length" select="string-length($data)"/> | |
<!-- More link --> | |
<xsl:param name="link"/> | |
<xsl:choose> | |
<!-- Return whole data if it's within length. --> | |
<xsl:when test="string-length($data) <= $length"> | |
<xsl:copy-of select="$data" /> | |
</xsl:when> | |
<!-- Truncate to desired length. --> | |
<xsl:otherwise> | |
<xsl:for-each select="$data/*"> | |
<xsl:variable name="this-node" select="string-length(.)"/> | |
<xsl:variable name="preceding-nodes"> | |
<xsl:copy-of select="preceding-sibling::*"/> | |
</xsl:variable> | |
<xsl:variable name="node-sum" select="string-length(normalize-space($preceding-nodes))"/> | |
<xsl:variable name="limit" select="$node-sum + $this-node"/> | |
<xsl:choose> | |
<xsl:when test="$limit > $length and $node-sum <= $length"> | |
<p> | |
<xsl:value-of select="substring(.,1,$length - $node-sum)"/> | |
<xsl:text>…</xsl:text> | |
<a> | |
<xsl:attribute name="href"> | |
<xsl:value-of select="$link"/> | |
</xsl:attribute> | |
<xsl:text>more</xsl:text> | |
</a> | |
</p> | |
</xsl:when> | |
<xsl:when test="$limit < $length"> | |
<xsl:copy-of select="."/> | |
</xsl:when> | |
<xsl:otherwise/> | |
</xsl:choose> | |
</xsl:for-each> | |
</xsl:otherwise> | |
</xsl:choose> | |
</xsl:template> | |
</xsl:stylesheet> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment