Search code examples
javascriptjavathymeleafoption-type

Use an Optional java variable in JS


I have an Optional variable passed from my Java back-end to my thymeleaf/js front-end, and I want to use it in a js script.

I tried this:

if ([[${appId.isPresent()}]]) actionURL = actionURL + "/app/" + [[${appId.get()}]];

but when appId is not present, I get a "no value present" java error for appId.get(). If I understand correctly, my problem is that the .get() method is called before the if condition is checked.

I suppose I can do the validation in thymeleaf and then pass the value (or "null") to js from there, but that doesn't feel right. Any better ideas?


Solution

  • Assuming [[{}]] is the templating then perhaps

    const appId = "[[${appId.isPresent() ? ${appId.get() : ""}]]";
    const actionURL += "/app/" + appId;
    

    or

    const actionURL = "/app/[[${appId.isPresent() ? ${appId.get() : ""}]]";