Adam
Adam

Reputation: 6132

How can I define an XSL variable and assign a value in xsl:choose

I want to define a variable named 'category' in XSL, assign a value to it, and reuse that variable a bit down in my code. if objecttype=1 the variable value should be 'car' if objecttype=2 the variable value should be 'bus'

How can I achieve that?

<xsl:template match="/">
<html>
<head><style type="text/css">body{font-size:11px;font-family:Verdana;}</style></head>
<body>
Dear
<xsl:for-each select="user">
<xsl:value-of select="firstname"/><xsl:text disable-output-escaping="yes">&amp;nbsp;</xsl:text>
<xsl:if test="middlename != ''"> 
<xsl:value-of select="middlename"/><xsl:text disable-output-escaping="yes">&amp;nbsp;</xsl:text>
</xsl:if>
</xsl:for-each>
<xsl:value-of select="user/lastname"/>,<br/>
<br/>
You have created a company listing for "<xsl:value-of select="user/objecttitle"/>".<br/>
<br/>
Did you know Google uses the number of Facebook 'likes' for webpages in its rankings?<br/>
You can like you page here: 
<xsl:for-each select="user"> 
<xsl:variable name="category"> 
    <xsl:choose> 
        <xsl:when test="objecttype='1'">car</xsl:when> 
        <xsl:when test="objecttype='2'">bus</xsl:when> 
    </xsl:choose> 
</xsl:variable> 
</xsl:for-each> 
<a href="http://www.mydomain.com/{$category}/{user/objectid}/{user/objecturl}">Click here to go to your company listing now.</a><br/>
Kind regards,<br/>
<br/>
<br/>
</body>
</html>
</xsl:template>

Upvotes: 4

Views: 6435

Answers (1)

Jim Garrison
Jim Garrison

Reputation: 86774

This is a common error for XSL newcomers. The correct approach is:

<xsl:variable name="category">
  <xsl:choose>
    <xsl:when test="objecttype='1'">car</xsl:when>
    <xsl:when test="objecttype='2'">bus</xsl:when>
    ... etc
  </xsl:choose>
</xsl:variable>

In your example, the variable is local to the <xsl:when...> tag.

Upvotes: 5

Related Questions