API / Apache FreeMarker Interview questions
How do you apply default values for missing variables in FreeMarker?
The default-value operator ! supplies a fallback when a variable is missing or null, so the template does not fail: ${nickname!"Guest"} prints the nickname if it exists, otherwise prints "Guest".
<p>Hello, ${user.nickname!"friend"}!</p> <#assign theme = settings.theme!"light">
It also works with nested property paths, where any segment along the chain might be missing, by wrapping the whole path: ${(user.profile.avatarUrl)!"/default.png"}. This is the idiomatic FreeMarker way to avoid the equivalent of a null-pointer failure without writing an explicit <#if> check for every optional value.
More Related questions...