Understanding Comparisons in FreeMarker Templates

When working with FreeMarker templates, you often need to compare values to determine equality or which value is greater. This guide will walk you through the basic comparison operations and how to use them effectively within your FreeMarker templates.

The if Directive

In FreeMarker, the if directive is used to evaluate conditions. The syntax for the if directive is as follows:

<#if expression>
  ...content...
</#if>

Here, the expression must evaluate to a boolean value. If the expression is true, the content between the opening and closing if tags will be processed; otherwise, it will be skipped.

Testing for Equality and Inequality

To test whether two values are equal, you use the == operator. For inequality, you use the != operator. Consider the following example where the variable user is assigned the value “Big Joe”:

<#if user == "Big Joe">
  It is Big Joe
</#if>
<#if user != "Big Joe">
  It is not Big Joe
</#if>

In this example, the expression user == "Big Joe" evaluates to true, so the output will be “It is Big Joe”.

Important Notes on Equality and Inequality

  • The expressions on both sides of the == or != operators must evaluate to scalar values (i.e., not sequences or hashes).
  • The two scalar values must be of the same type; for example, strings can only be compared to strings, and numbers can only be compared to numbers. Comparing different types, like <#if 1 == "1">, will result in an error.
  • FreeMarker performs exact comparisons, which means string comparisons are case-sensitive and white-space sensitive. For instance, "x" and "X" are not considered equal.

Numerical and Date Comparisons

For numerical and date values, you can use the comparison operators <, <=, >=, and >:

<#if x <= 12>
  x is less or equivalent to 12
</#if>

However, there is a caveat with the >= and > operators. FreeMarker interprets the > character as the closing character of an FTL tag. To avoid this issue, you can use alternative operators or syntax:

  • Use lt instead of <
  • Use lte instead of <=
  • Use gt instead of >
  • Use gte instead of >=

For example:

<#if x gt y>
  x is greater than y
</#if>

Alternatively, you can enclose the expression in parentheses:

<#if (x > y)>
  x is greater than y
</#if>

Additional Syntactical Alternatives

FreeMarker supports additional syntactical alternatives for comparison operators:

  • &gt; and &lt; can be used, such as in <#if x &gt; y> or <#if x &gt;= y>. This is useful when the template gets XML/HTML escaped.
  • Deprecated forms: lt, lte, gt, and gte. These perform the same functions as their counterparts without the backslash.

Leave a comment

Your email address will not be published. Required fields are marked *