Widon't XSLT
Typography Beautifier
Description
Remove unsightly widows by adding a non-breaking space between the last two words in a string. Gist link.
XSLT
View Raw
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <!-- Name: Widon't Version: 1.0 Author: Oleg Kurapov URL: http://www.2sheds.ru/blog/2007/06/widont-in-xslt-dont-be-a-widow-maker/ Description: Remove unsightly widows by adding a non-breaking space between the last two words in a string. Apply the template with param named `text` and use `normalize space` to remove any extra space at the end of the string. <xsl:call-template name="widont-title"> <xsl:with-param name="text" select="normalize-space(fields/title)" /> </xsl:call-template> If the combined length of two last words is longer than the character length defined in the `maxlen` parameter, the non-breaking space is not added. This prevents the opposite of widows: orphans. Feel free to adjust that parameter. Credit: Based on Shaun Inman's Wordpress plugin. http://shauninman.com/archive/2006/12/05/widont_2_wordpress_plugin --> <xsl:template name="widont-title"> <xsl:param name="temp"/> <xsl:param name="text"/> <xsl:param name="maxlen" select="35"/> <xsl:choose> <xsl:when test="contains($text, ' ')"> <xsl:variable name="prev" select="substring-before($text,' ')"/> <xsl:variable name="before" select="concat($temp,' ',$prev)"/> <xsl:variable name="after" select="substring-after($text, ' ')"/> <xsl:choose> <xsl:when test="contains($after, ' ')"> <xsl:call-template name="widont-title"> <xsl:with-param name="temp" select="$before"/> <xsl:with-param name="text" select="$after"/> </xsl:call-template> </xsl:when> <xsl:when test="not(contains($after, ' ')) and string-length(concat($prev,$after)) < $maxlen"> <xsl:value-of select="concat($before, ' ', $after)" /> </xsl:when> <xsl:otherwise> <xsl:value-of select="concat($before, ' ', $after)" /> </xsl:otherwise> </xsl:choose> </xsl:when> <xsl:otherwise> <xsl:value-of select="$text"/> </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet>