Reputation: 295
I know this may seem like a dumb/newbie question, but I'm fairly new to XSLT (though I'm starting to come around to it and see it's capabilities).
When is it appropriate to use xsl:if and when is it appropriate to use xsl:choose/xsl:when?
I have been using choose/when/otherwise when I want to have an "else" option. Is this correct?
For instance I have some places where I'm doing:
<xsl:choose>
<xsl:when test="count(entry) != 0">
put positive outcome here
</xsl:when>
<xsl:otherwise>
put something else here
</xsl:otherwise>
</xsl:choose>
would xsl:if be better?
Thanks for the input.
Upvotes: 3
Views: 6611
Reputation: 239784
would xsl:if be better?
Not really - unless you want to have two xsl:if
s and ensure that their conditions are mutually exclusive.
an xsl:choose
will always select exactly one of the available xsl:when
or xsl:otherwise
The
<xsl:when>
children of the<xsl:choose>
element are tested, in order from top to bottom, until a test attribute on one of these elements accurately describes conditions in the source data, or until an<xsl:otherwise>
element is reached. Once an<xsl:when>
or<xsl:otherwise>
element is chosen, the<xsl:choose>
block is exited. No explicit break or exit statement is required.
It's remarkably similar to a switch
statement from C inspired languages (C, C++, Java, C#) or Select...Case
from Visual Basic
The xsl:if
doesn't have the equivalent from such languages of an else
clause, so I'd only recommend it if you want to either do "something" or not (I.e. in the not case, you don't want to specify an alternative)
Upvotes: 4
Reputation: 405995
Use xsl:if
for simple cases where you just want to test if an expression is true. (Note that there is no corresponding xsl:else
.)
<xsl:if test="expression">
output if the expression is true
</xsl:if>
Use xsl:choose
for cases where you have some alternate output when the expressions is false.
<xsl:choose>
<xsl:when test="expression">
output if the expression is true
</xsl:when>
<xsl:otherwise>
output if the expression is false
</xsl:otherwise>
</xsl:choose>
Upvotes: 9