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]
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).
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.
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!)
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.
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()!''}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With