How to default a variable in XSLT

Since I couldn’t find this anywhere on the web, and I’m working on a project that has had me very quickly learn XSLT, here’s how to default a value in XSLT – useful if you’re looking to grab a variable via the query string, and it may not be there in the first place.

<xsl:variable name="show_comments">
  <xsl:choose>
    <xsl:when test="//QUERY_STRING/show_comments"><xsl:value-of select="//QUERY_STRING/show_comments"/></xsl:when>
    <xsl:otherwise>0</xsl:otherwise> <!-- default value -->
  </xsl:choose>
</xsl:variable>

Note: //QUERY_STRING is a made up variable

I know XSLT might be a bit random for me, but client wants: client gets :-)

4 Responses to “How to default a variable in XSLT”

  1. Only way I know of, too.

  2. XSLT is fun :)
    It’s important to realize though that it has several limitations, and certain things are a real PITA to do in it.
    That’s where using Saxon or some other XSLT processor that lets you extend XSLT with your own functions/methods written in a more powerful langauge like Java or C.

  3. Depending on how you’re using the variable, sometimes it is easier to use a parameter inside a template since they support default values

  4. I found a way, which i think is easier:

    <xsl:variable name="language" select="if (/data/context/language/@id) then /data/context/language/@id else 'de'"/>

Leave a Reply
Not required

CODE: Please escape code and wrap in <pre><code>, doing so will automatically syntax highlight