choose/when/otherwise

choose provides a multi choice statement equivalent to a switch statement in languages such as Swift or C. Like these languages it provides for default conditions when all the suggested alternatives fail.

Switch cases use the when keyword with a test and an enclosed block if that test is true. If none of the cases is true then, either the choose statement exits, or the otherwise block is run.

Syntax
<choose> ::= "choose" "{” <when>+ <otherwise>? “}” <when> ::= "when" <test> "{" <block templates>+ "}" <otherwise> ::= "otherwise" "{" <block templates>+ "}"
Options

None

Required Elements

One or more when blocks.

Examples

As an example the following sets a variable gPageTitle dependent on a condition.

'string-length(//page:meta/page:pageTitle) > 0'

and gives a default value. In this case it is equivalent to a if ... then ... else ....

variable gPageTitle { choose { when "string-length(//page:meta/page:pageTitle) > 0" { value "//page:meta/page:pageTitle" } otherwise { value "'Paloose'" } } }

will result in

<xsl:variable name="gPageTitle"> <xsl:choose> <xsl:when test="string-length(//page:meta/page:pageTitle) > 0"> <xsl:value-of select="//page:meta/page:pageTitle"/> </xsl:when> <xsl:otherwise> <xsl:value-of select="'Paloose'"/> </xsl:otherwise> </xsl:choose> </xsl:variable>

A slightly larger, multi choice, example might be

choose { when "@type = 'dir'" { element "span" { attribute "class" "code-dir" apply-templates scope "inline-text" } } when "@type = 'var'" { element "span" { attribute "class" "code-var" apply-templates scope "inline-text" } } when "@type = 'tag'" { element "span" { attribute "class" "code-dir" text "&lt;" apply-templates scope "inline-text" text "&gt;" } } otherwise { apply-templates scope "inline-text" } }
Errors

The most common error is misspelling.

variable gPageTitle { choose { when "string-length(//page:meta/page:pageTitle) > 0" { value "//page:meta/page:pageTitle" } otherwie { text "Paloose" } } }

will produce the error (together with potential consequential errors)

**** (106) Unexpected symbol "otherwie" in line 10 Check spelling, did you mean "otherwise" ? **** (106) Unexpected symbol "{" in line 10 Check spelling, no suggestion. **** (136) Unmatched brackets in 1 Too many open brackets?
Copyright 2024 Hugh Field-Richards. All Rights Reserved.