Wrapping Text to a Specified Width and Alignment
Problem
You want to format multilined text within an XML document into a fixed-width-aligned format, insuring that lines wrap at word boundaries.
Solution
Here is a solution that handles both wrapping and alignment by
reusing the text:justify
template constructed in
Recipe 5.3. For added flexibility, you can allow
the alignment width to be specified separately from wrapping width,
but default to it when unspecified:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" id="text.wrap" xmlns:str="http://www.ora.com/XSLTCookbook/namespaces/strings" xmlns:text="http://www.ora.com/XSLTCookbook/namespaces/text" exclude-result-prefixes="text"> <xsl:include href="../strings/str.find-last.xslt"/> <xsl:include href="text.justify.xslt"/> <xsl:template match="node( ) | @*" mode="text:wrap" name="text:wrap"> <xsl:param name="input" select="normalize-space( )"/> <xsl:param name="width" select="70"/> <xsl:param name="align-width" select="$width"/> <xsl:param name="align" select=" 'left' "/> <xsl:if test="$input"> <xsl:variable name="line"> <xsl:choose> <xsl:when test="string-length($input) > $width"> <xsl:call-template name="str:substring-before-last"> <xsl:with-param name="input" select="substring($input,1,$width)"/> <xsl:with-param name="substr" select=" ' ' "/> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:value-of select="$input"/> </xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:if test="$line"> <xsl:call-template ...
Get XSLT Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.