Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]

like image 462
user1684651 Avatar asked Dec 16 '16 06:12

user1684651


People also ask

How do you add values on FreeMarker?

Interpolation and concatenation. If you want to insert the value of an expression into a string, you can use ${...} (and the deprecated #{...} ) in string literals. ${...} in string literals behaves similarly as in text sections (so it goes through the same locale sensitive number and date/time formatting).

How does FreeMarker handle null values?

The most common method of detecting for empty or null values uses the has_content function and the trim function. The has_content function is often used with another built-in FreeMarker function to detect for null values. Check the FreeMarker documentation for more information on the has_content function.

How do I print a value in FreeMarker?

For example, if you create a variable called "foo" in the template, you can print its value with ${foo} . If, coincidently, there's a variable called "foo" in the data-model too, the variable created in the template will hide (not overwrite!)

Is FreeMarker template thread safe?

getTemplate(String) (and its overloads) does that (caching Template -s) for you, but the constructor of course doesn't, so it's up to you to solve then. Objects of this class meant to be handled as immutable and thus thread-safe.


1 Answers

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()!''}
like image 134
marknorkin Avatar answered Oct 03 '22 03:10

marknorkin