Skip to content

Instantly share code, notes, and snippets.

@MrBlank
Last active August 24, 2022 14:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MrBlank/208770 to your computer and use it in GitHub Desktop.
Save MrBlank/208770 to your computer and use it in GitHub Desktop.
Remove unsightly widows by adding a non-breaking space between the last two words in a string.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<!--
Name: Widon't XSLT
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)) &lt; $maxlen">
<xsl:value-of select="concat($before, '&#160;', $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>
@kirkstrobeck
Copy link

Nice !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment