如何在Thymeleaf中根据请求参数条件添加自定义属性?
问题:Spring Boot中Thymeleaf根据请求参数为form添加自定义属性报错
我在Spring Boot项目中使用Thymeleaf时,想要根据请求中的参数为form标签添加自定义属性,模板代码如下:
<form class="..." id="form-login" method="post" th:action="@{/processlogin}" th:classappend="${param.error}? 'show' : ''" th:attr="abc=${param.error ? '123'}" >...
运行时抛出异常:
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)
我尝试修改为th:attr="abc=${param.error} ? '123'",仍然出现相同错误。我查阅了相关资料和Thymeleaf文档,文档只展示了条件添加类的示例,没有涉及自定义属性的条件设置,使用的Thymeleaf版本是3.1.3,请问该如何解决?
解决方案
通过先使用th:with定义变量,再在th:attr中引用变量的方式解决,代码如下:
th:with="withError=${param.error}? '123' : ''" th:attr="abc=${withError}"
内容的提问来源于stack exchange,提问作者Atatorus
相关产品推荐
相关产品推荐

