I want add a custom attribute in a form tag according a parameter in request with thymeleaf and spring boot. Here an example extracted of my template :
<form class="..." id="form-login" method="post" th:action="@{/processlogin}"
th:classappend="${param.error}? 'show' : ''"
th:attr="abc=${param.error ? '123'}"
>...
But I get an exception :
Caused by: org.attoparser.ParseException: Instantiation of new objects and access to static classes or parameters is forbidden in this context (template: "fragments/login" - line 3, col 7)
I tried with th:attr="abc=${param.error} ? '123'
, I get the same error. I saw this question and this other, but without result. And the documentation of thymeleaf show examples to add conditional classes, but not attributes.
I use thymeleaf in version 3.1.3.
What is the solution ? Thanks for your help.
Edit : thanks the answers of DarkBee and Slava Ivanov, I resolved my problem. Here the solution :
th:with="withError=${param.error}? '123' : ''" th:attr="abc=${withError}"
The problem is that you didn't read the exception description carefully, instead, you assumed that the issue was with the syntax of th:attr
tag. The syntax you have used in your post example is correct, and you need to concentrate on the exception you are getting.
From the quick copy & paste into Google, the result comes up right away about the restriction Thymeleaf made more than 3 years ago on the execution of static code in certain tags (I believe this was introduced in v.3.0). You may read more on this change at Improve restricted expression evaluation mode.
Now, when you know the Thymeleaf improvements in this area, the issue you are observing is actually with param
object. There are a few workarounds to solve it. The simplest one is to use th:with
tag where to put your condition, and in th:attr
tag just use the variable you set. Unfortunately, I don't have an environment to try it myself right now, but the code should look similar to (or you'll figure it out) ...
<div th:with="varName=${param.error? 'show' : ''}" th:attr="abc=${varName}"></div>