Search code examples
xsltxslt-2.0

Setting a value in a variable on if conditions using XSL


I have a basic condition that checks if a variable is empty and if it is set the variable to a specific value like so.

<xsl:variable name="PIC" select="avatar"/>

<xsl:choose>
  <xsl:when test="avatar !=''">
    <xsl:variable name="PIC" select="avatar"/>
  </xsl:when>
  <xsl:otherwise>
    <xsl:variable name="PIC" select="'placeholder.jpg'"/>
  </xsl:otherwise>
</xsl:choose>

Basically var PIC is set to whatever avatar returns. Then a test is carried to check if if it's not empty and assigned to var PIC and if it is empty a value placeholder.jpg is added to var PIC instead.

Now for some reason I keep getting the following warning

A variable with no following sibling instructions has no effect

Any ideas on what I am doing wrong here?


Solution

  • Variables are immutable in XSLT, and cannot be changed once set. The variable declarations in the xsl:choose are simply new declarations that at local in scope to the current block. (They are said to "shadow" the initial variable).

    What you need to do is this...

    <xsl:variable name="PIC">
       <xsl:choose>
         <xsl:when test="avatar !=''">
            <xsl:value-of select="avatar"/>
         </xsl:when>
         <xsl:otherwise>
           <xsl:value-of select="'placeholder.jpg'"/>
         </xsl:otherwise>
       </xsl:choose>
    </xsl:variable>