Many times I come across situations where I need to write a lot of extra code to get things to work without errors when a variable might be undefined.
In the example below, I have a form that I want to fill with populated values when they are available and leave the values blank when they are not. According to various Thymeleaf help sites (here and others), the following should work: ${user?.name} as you can see in the input below:
But it does not work, even when āuserā is not null or undefined. Instead I have to make two versions of the form and then I get IntelliJ errors due to duplicate ids.
That still leaves me duplicating most of the form, but if ${user?.name} worked then I wouldnāt have to. I want each input to render no matter what. That way I could use the same form to create a content, or edit an existing content.
I just set this up for a form Iām working on. On error I send the āmessageā JSON full of info, and all the sent input fields as washed (āsafeā) strings back so I can populate the fields again (to assist user in correct their errors).
When testing this little Thymeleaf snippet I actually got this working, could it work for you?
data-th-value="${user ? user.name : āā }" should work for setting an empty value if the user is null.
If only user.name is null or undefined, you shouldnāt need any checks.
In my form application (beta will be released in a few days), I use this frequently.
Actually, I use this bit for (almost) any html5 input type (except e.g. radio buttons or selects, which have different markup):
Most attributes are undefined for a single input type, but that is not relevant. However, for input.datalist.id, I do a check to see if input.datalist is defined.
Which seems like something similar to the approach I use, though I donāt know the #-syntax.
I can do some more testing, but I havenāt had any problems with this yet.