Skip to content

Instantly share code, notes, and snippets.

@nickdunn
Created March 28, 2010 18:42
Show Gist options
  • Save nickdunn/346948 to your computer and use it in GitHub Desktop.
Save nickdunn/346948 to your computer and use it in GitHub Desktop.
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exsl="http://exslt.org/common"
xmlns:str="http://exslt.org/strings"
extension-element-prefixes="exsl str">
<xsl:template match="data">
<xsl:call-template name="split-into-spans">
<xsl:with-param name="text" select="'The quick brown fox jumped over the lazy dog.'"/>
<xsl:with-param name="limit" select="'4'"/>
</xsl:call-template>
<!--
<span>The quick brown fox </span>
<span>jumped over the lazy </span>
<span>dog.</span>
-->
</xsl:template>
<xsl:template name="split-into-spans">
<xsl:param name="text"/>
<xsl:param name="limit"/>
<!-- split into words -->
<xsl:variable name="tokens" select="str:tokenize($text)"/>
<xsl:variable name="total-tokens" select="count($tokens)"/>
<!-- loop over every n-th word -->
<xsl:for-each select="$tokens[position() mod $limit = 0]">
<xsl:variable name="position" select="position()"/>
<xsl:variable name="start" select="($limit * $position) - ($limit - 1)"/>
<xsl:variable name="end" select="($limit * $position)"/>
<!-- add the words from the previous word until this word -->
<span>
<xsl:for-each select="$tokens[position() &gt;= $start and position() &lt;= $end]">
<xsl:value-of select="concat(text(), ' ')"/>
</xsl:for-each>
</span>
</xsl:for-each>
<!-- if the total isn't divisible exactly, add remaining words -->
<xsl:variable name="remainder" select="$tokens[position() &gt; ($total-tokens - ($total-tokens mod $limit))]"/>
<xsl:if test="$remainder">
<span>
<xsl:for-each select="$remainder">
<xsl:value-of select="concat(text(), ' ')"/>
</xsl:for-each>
</span>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment