Padding text output to the right width in XSLT
(I originally added this to one of my other web sites back in November 2005. Now I'm bunching all my stuff into this one blog, so here it is again).
I worked this out while writing some XSLT that was supposed to generate a text file. I thought I needed to pad the fields with spaces to get them to the right width, but actually I don't, it is delimited text not fixed width.
I case I ever do need to pad text fields, here's how I did it.
<!-- this is the function for making a field the right width -->
<xsl:template name="leftjustify">
<xsl:param name="content">
<xsl:param name="width">
<xsl:choose>
<xsl:when test="string-length($content) > $width">
<xsl:value-of select="substring($content,1,$width)">
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$content">
<xsl:call-template name="spaces">
<xsl:with-param name="length"><xsl:value-of select="$width - string-length($content)"></xsl:with-param>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template name="spaces">
<xsl:param name="length">
<!-- the value of this next variable is 255 spaces.. -->
<xsl:variable name="longstringofspaces"><xsl:text> </xsl:text></xsl:variable>
<xsl:value-of select="substring($longstringofspaces,1,$length)">
</xsl:template>
There's two named templates (read, functions), "spaces" that returns a specified number of spaces (up to 255), and one that uses spaces to do truncation or left-justification. Call it like this:
<xsl:call-template name="leftjustify">
<xsl:with-param name="content">this is too short</xsl:with-param>
<xsl:with-param name="width">40</xsl:with-param>
</xsl:call-template>
and the result will be the text "this is too short" with 23 spaces after it (making it 40 chars long).
2 comments:
These are very useful templates, but there are a few typos in it (or the characters got lost somewhere).
There are about 5 missing / characters before closing >'s, p.e. <xsl:param name="content">. There should be a / before >.
Carl.
I am very new to the XSLT and I just wanted to say that these were very useful templates and I understood them very easily. Thanks a bunch.
Post a Comment