user1684651
user1684651

Reputation: 430

FreeMarker Java 8 Optional value support

Does FreeMarker support Optional value in Java 8?

e.g. I have String id, and its getter method is like:

public Optional<String> getId() {
  return Optional.ofNullable(Id);
}

How am I going to reference it in the .ftl file. It seems that {data.id} can not find the correct Optional value. But gives me Optional[1334586]

Upvotes: 7

Views: 5018

Answers (1)

marknorkin
marknorkin

Reputation: 4074

Well, Freemarker is not supposed to be aware of Optional or it is better to say that its dynamically typed so it works for any object.

Since you calling ${data.id} it's just calls toString on Optional which is totally expected behavior.

If you want to handle null values in your template and for that you want to use Optional, you may choose to set a default value if null, so Optional usage won't be needed:

    Synopsis: unsafe_expr!default_expr or unsafe_expr! or (unsafe_expr)!default_expr or (unsafe_expr)!
    Example: ${data.id!"No id."}

Or check if it's exists:

<#if data?? && data.id??>
  Id found
<#else>
  Id not found
</#if>

For more info check out the Freemarker docs. Specifically parts: Handling missing values and Missing value test operator.

If you just want to get the value from Optional in your template:

${data.id.orElse('')}

or

${data.id.get()!''}

Upvotes: 9

Related Questions