Multiple choices

When one option is to be selected from a number of possible options, the If element can be used repeatedly. But, the fact that each If element is independent of the others can be inconvenient in some circumstances. It is not possible to prevent more than one of the tests from succeeding (if this is desired), and it is not possible to take specific action if none is triggered. Both of these constraints could be overcome if a set of tests could be treated as a group.

The Choose element encloses a number of alternative fragments of the template that should apply under different circumstances. Each alternative is defined using the When element, which works in exactly the same way as the If element described previously. The condition is defined using the Test attribute. At least one When element must be present within the Choose element, and these elements may not be used anywhere else:

<choose>
  <when
					test="...">
    <!-- OPTIONAL FRAGMENT OF TEMPLATE -->
    ...
  </when>
  <when
					test="...">
    <!-- OPTIONAL FRAGMENT OF TEMPLATE -->
    ...
  </when>
</choose>

Grouping of the When elements in this way makes it feasible for them to be treated as a whole. First, it becomes possible to ensure that only one is selected, even when more than one contains an expression that succeeds. It also becomes possible to recognize when none of the tests was successful, and to perform some default action when this is the case.

The order in which the When elements are placed within the Choose element can be very important, because only the first successful test is obeyed. In the following example, the two tests on the Colour attribute are only reached for elements that do not have a Type value of 'secret':

<choose>
  <when test="@type='secret'">
    <!-- ADD NOTHING - COLOUR NOT SIGNIFICANT -->
  </when>
  <when test="@color='blue'">
    <text>BLUE TEXT - NOT SECRET</text>
  </when>
  <when test="@color='green'">
    <text>GREEN TEXT - NOT SECRET</text>
  </when>
</choose>

The optional Otherwise element has no attributes, as its content is always selected when none of the When elements is relevant. It is never activated when a test succeeds.

<choose>
  <when test="@color='blue'">
    <text>BLUE TEXT</text>
  </when>
  <when test="@color='green'">
    <text>GREEN TEXT</text>
  </when>
  <otherwise>
    <text>DEFAULT TEXT - ALL COLOURS
					EXCEPT BLUE AND GREEN</text>
  </otherwise>
</choose>

The Otherwise element must appear after the list of When elements, immediately before the Choose element end-tag.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset