Instead of lingering on theory too much, let's do something useful while learning
XSLT 2.0 you can write the following:
<!-- example of a short `if-then-else` statement --> <xsl:variable as="xs:boolean" name="shortIf" select="if ('a' = 'b') then 'wrong?' else 'right!'" />
Unfortunately, using BI Publisher, the exact same expression in the
<xsl:value-of> element fails to compile:
<!-- example of a short `if-then-else` statement (does not compile) --> <xsl:value-of select="if ('a' = 'b') then 'wrong!' else 'right!'" />
Unless I read it wrong, this is non-compliant with the
XSLT 2.0 specification. In any case, it is very annoying as writing it the long way, i.e. using
<xsl:choose> would make your style sheets twice as long. Using
<xsl:variable> every single time to achieve this would be slightly better but still very cumbersome and verbose.
What I would like to be able to write instead is the following:
<!-- helper function usage (declared below) --> <xsl:value-of select="utils:ifElse('a' = 'b', 'wrong!', 'right!')" />
This is, actually, even more concise - and readable! - than the original short
if-then-else expression! Let's create a function that enables us to achieve this:
<!-- helper function declaration --> <xsl:function name="utils:ifElse"> <xsl:param name="condition" /> <xsl:param name="true" /> <xsl:param name="false" /> <xsl:variable name="result" select="if ($condition) then $true else $false" /> <xsl:value-of select="$result" /> </xsl:function>
In order for this code to compile, you need to add the following namespace declaration to the opening tag of your
XSL style sheet:
... and you're good to go!
Even though I feel most of the code is quite self-explanatory, let's make sure everybody's on the same page:
<xsl:function name="utils:ifElse">declares a function called
- Individual parameters of a function are specified using the
<xsl:param>which can be accessed in the scope of a function using their
- A function returns the evaluation of the last
<xsl:value-of>(or the last node or set of nodes present in the function declaration).