I'm trying to use a template that appends white space to a string.
<xsl:call-template name="append-pad">
<xsl:with-param name="padChar" select="' '" />
<xsl:with-param name="padVar" select="$value" />
<xsl:with-param name="length" select="15" />
</xsl:call-template>
<xsl:template name="append-pad">
<!-- recursive template to left justify and append -->
<!-- the value with whatever padChar is passed in -->
<xsl:param name="padChar" />
<xsl:param name="padVar" />
<xsl:param name="length" />
<xsl:choose>
<xsl:when test="string-length($padVar) < $length">
<xsl:call-template name="append-pad">
<xsl:with-param name="padChar" select="$padChar" />
<xsl:with-param name="padVar" select="concat($padVar,$padChar)" />
<xsl:with-param name="length" select="$length" />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="substring($padVar,1,$length)" />
</xsl:otherwise>
</xsl:choose>
</xsl:template>
But the length of the with space is dynamic. This is what I tried in javascript but I get an error saying 'NAME cannot begin with '' when trying to debug the xslt.
function firstName(name) {
try {
var n = name.toString;
var target = name.length - 20;
var whiteString = "";
for ( i = 0; i < target; i++) {
whiteString.concat(" ");
}
n = n + whiteString;
return n;
} catch(err) {
return " ";
}
}
How can I do this logic in xslt?
<xsl:value-of select="concat(substring(' ', string-length() +1), $firstName)"/>
If, from your JavaScript example, you always want to pad the string up to a maximum of 20 characters, then you can simply use:
<xsl:value-of select="concat(substring(' ', string-length($firstName) +1), $firstName)" />
How does this work?
First take the expression: substring(' ', string-length($firstName) +1)
This will take the string of 20 spaces, and return a string of spaces that is 20 - length of $firstName as we are using substring to only extract a portion of the string.
We then use the concat function to join the two together. We put the substring of spaces first to pad left (although we could always put them second if you wanted to pad right).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With