RE: [xsl] word wrap in text string

Subject: RE: [xsl] word wrap in text string
From: "Michael Kay" <michael.h.kay@xxxxxxxxxxxx>
Date: Mon, 11 Mar 2002 09:22:18 -0000
> Hi MIchale,
> thanks for time and effort,if possible can you give me a more
> detail example
> of extension function or pre/post processing like some code
> example or
> someting on web or book.I will be really thankfull.

You'll find plenty of examples of extension functions in my XSLT book. But I
mentioned preprocessing and postprocessing because it's often an easier
option and people don't always think of it. You can do this using either DOM
or SAX interfaces, and you will find examples of DOM or SAX applications in
any general XML textbook: there is nothing specific to XSLT about this.

> I tried to use following code but it did'nt work because of recursion
> <xsl:template name="textwrapzz">
> 	<xsl:param name="Text"/>
> <xsl:value-of select="substring(Text, 1, 30)"/>
> <br></br>
>   <xsl:variable name="rest" select="substring($Text, 31)" />
>   <xsl:if test="string-length($rest) &gt; 30">
>     <xsl:call-template name="textwrap">
>       <xsl:with-param name="Text" select="$rest" />
>     </xsl:call-template>
>   </xsl:if>
> </xsl:template>

It didn't work (a) because in line 3 you need to refer to "$Text" rather
than "Text", and (b) because you don't do anything with $rest if it's less
than 30 characters. The following should work:

> <xsl:template name="textwrap">
> 	<xsl:param name="Text"/>
  <xsl:choose>
  <xsl:when test="string-length($Text) &gt; 30">
    <xsl:value-of select="substring($Text, 1, 30)"/>
    <br></br>
>     <xsl:call-template name="textwrap">
>       <xsl:with-param name="Text" select="substring($Text, 31)" />
>     </xsl:call-template>
> </xsl:when>
  <xsl:otherwise><xsl:value-of select="$Text"/></xsl:otherwise>
> </xsl:template>

Of course this won't be a very elegant way of wrapping the text since it's
not looking for word boundaries. To solve that problem I would output one
word (up to a space) in each recursive call, passing an extra parameter that
indicates the number of characters written to the current line, and
outputting the <br/> element when this reaches 30.

Michael Kay
Software AG
home: Michael.H.Kay@xxxxxxxxxxxx
work: Michael.Kay@xxxxxxxxxxxxxx

>


 XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list


Current Thread