switch, case, default, break - FreeMarker Manual

- Home
- Manual
- Java API

- Contribute
- Report a Bug
- Download

Manual
Previous Next

# switch, case, default, break

## Synopsis

    <#switch value>
      <#case refValue1>
        ...
        <#break>
      <#case refValue2>
        ...
        <#break>
      ...
      <#case refValueN>
        ...
        <#break>
      <#default>
        ...
    </#switch>

Where:

- `value`, `refValue1`, etc.: Expressions evaluates to scalars of the same type.

The `break`-s and `default` are optional.

## Description

The usage of this directive is not recommended, as it's error-prone because of the fall-through behavior. Use `elseif`-s instead unless you want to exploit the fall-through behavior.

Switch is used to choose a fragment of template depending on the value of an expression:

    <#switch animal.size>
      <#case "small">
         This will be processed if it is small
         <#break>
      <#case "medium">
         This will be processed if it is medium
         <#break>
      <#case "large">
         This will be processed if it is large
         <#break>
      <#default>
         This will be processed if it is neither
    </#switch>

Inside the `switch` must be one or more `<#case value>`, and after all such `case` tags optionally one `<#default>`. When FM reaches the `switch` directive, it chooses a `case` directive where `refValue` equals with `value` and continues the processing of the template there. If there is no `case` directive with appropriate value then it continues processing at the `default` directive if that exists, otherwise it continues the processing after the end-tag of `switch`. And now comes the confusing thing: when it has chosen a `case` directive, it will continue the processing there, and will go ahead until it reaches a `break` directive. That is, it will not automatically leave the `switch` directive when it reaches another `case` directive or the `<#default>` tag. Example:

    <#switch x>
      <#case 1>
        1
      <#case 2>
        2
      <#default>
        d
    </#switch>

If `x` is 1, then it will print 1 2 d; if `x` is 2 then it will print 2 d; if `x` is 3 then it will print d. This is the mentioned fall-through behavior. The `break` tag instructs FM to immediately skip past the `switch` end-tag.

Previous Next