Creating “Dynamic” XSL Variables


One of the really ugly things about working with Xsl is that it doesn’t support actual variables. There is a ‘variable’ element but it isn’t actually a variable; it is a constant as the value cannot be changed once it has been set. This leads to all sorts of horrible solutions, like duplicating Xsl for the various possible values/conditions or even turning a block of Xsl into a template and then passing parameters to it every time that value is needed. The latter works and is supported but is frequently overkill.

However, there is another way to do this. Simply move the conditional logic needed to set the variable’s value to within the variable declaration itself.

  <xsl:variable name="myVariable">
    <xsl:choose>
      <xsl:when test="someVariable = aValue">
        <xsl:value-of select="oneValue"/>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="anotherValue"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:variable>

This is still not as clean as I would like but allows for the variable to be set conditionally in one place so that it can be used easily elsewhere in the Xsl without having to worry about passing template parameters and so forth.

About these ads

Posted on January 31, 2013, in Development, Tips. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 123 other followers