Type independent built-ins

These are the built-ins that don't care (much) about the type of their left hand argument.

switch

Note:

This built-in exists since FreeMarker 2.3.23.

This is basically the in-line (expression) version of the switch-case-default directives. Its generic format is like matchedValue?switch(case1, result1, case2, result2, ... caseN, resultN, defaultResult), where defaultResult can be omitted. Example:

<#list ['r', 'w', 'x', 's'] as flag>
  ${flag?switch('r', 'readable', 'w' 'writable', 'x', 'executable', 'unknown flag: ' + flag)}
</#list>
  readable
  writable
  executable
  unknown flag: s

That is, switch will find the first case parameter (left to right) whose value equals to matchedValue, then it returns the value of the result parameter that's directly after that case parameter. If it doesn't find an equal case, then it will return the value of the defaultResult, or if there's no defaultResult parameter (i.e., if the number of parameters is even) then it stops the template processing with error.

Further details:

Note:

If you need to switch by a boolean value, you should use the then built-in instead, like matchedBoolean?then(whenTrue, whenFalse).

Note:

If you need to do arbitrary logical tests instead of simple equality comparisons at the case parameters, you can do something like this (here we tests for ranges): true?switch(priority <= 1, "low", priority == 2, "medium", priority >= 3, "high")

上一章 首页 下一章