It's 2020 and Thymeleaf still doesn't support Optional from Java 8, released six year ago. What are the workarounds?
I'm using Spring Boot 2.3.3.RELEASE with Thymeleaf. I have an object of type Foo that the controller provides via the model/session as foo. It has a method findName() that returns Optional<String>. So I can put this in my template:
[[${foo.findName()}]]
Assuming the name is "bar", that shows:
Optional[bar]
That works, but obviously it's not what I want.
So I tried what I would do in Java. The following should print simply the name (e.g. foo), or _____ if the name is missing:
[[${foo.findName().orElse("_____")}]]
Unfortunately that produces an exception:
org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression: ""
Trying to use conditions, this will provide the value if it is present:
[[${foo.findName().isPresent()} ? ${foo.findName().get()}]]
But for some reason this throws an exception:
[[${foo.findName().isPresent()} ? ${foo.findName().get()} : '_____']]
First, I'm not sure why the example using orElse() doesn't work, as the Optional instance is an object like any of the others. Secondly, does anyone know a workaround? Thirdly, does anyone know of a workaround that is concise and doesn't take up three times the code?
(What we really need is native support in Thymeleaf so that ${foo.findName()} ?: '_____' will just work naturally.)