XSL for Line breaking long words

I spent a few hours searching for, but had no luck in finding this. So I’m posting what I wrote!

This XSL will put a zero length space character into any word longer then 20 characters in any text node of the current XML document.

There is of course always better ways to do things, but this is what I came up with, if anyone has suggestions or feedback, I would love to hear it.

Thanks
Enjoy!

<xsl:template match="text()">
<!– We do some character transformations first–>
<xsl:choose>
<!– No need to progress further in the entire element is less then 20 characters
Change these two lines if you want to alter the max length of the word
–>
<xsl:when test="string-length($str) &gt; 20">
<xsl:call-template name="linebreaklongwords">
<xsl:with-param name="str" select="$str" />
<xsl:with-param name="len" select="20" />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$str"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>

<!– Break words longer then len characters –>
<xsl:template name="linebreaklongwords">
<xsl:param name="str"/>
<xsl:param name="len"/>
<xsl:for-each select="tokenize($str,’s’)">
<xsl:choose>
<xsl:when test="string-length(.) &gt; $len">
<xsl:call-template name="linebreaklongwordsub">
<xsl:with-param name="str" select="." />
<xsl:with-param name="len" select="$len" />
<!– zero length space –>
<xsl:with-param name="char"><xsl:text>​</xsl:text></xsl:with-param>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:choose>
<xsl:when test="position()=last()">
<xsl:copy-of select="."/>
</xsl:when>
<xsl:otherwise>
<xsl:copy-of select="."/><xsl:text> </xsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:template>

<xsl:template name="linebreaklongwordsub">
<xsl:param name="str"/>
<xsl:param name="len"/>
<xsl:param name="char"/>
<xsl:choose>
<xsl:when test="string-length($str) &gt; $len">
<xsl:value-of select="substring($str,1,$len)"/>
<xsl:value-of select="$char"/>
<xsl:call-template name="linebreaklongwordsub">
<xsl:with-param name="str" select="substring($str,$len + 1)" />
<xsl:with-param name="len" select="$len" />
<xsl:with-param name="char" select="$char" />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$str"/><xsl:text> </xsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:template>

This entry was posted in internet, programming, tech. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s