我试图在 Thymeleaf 3.0.3 (Spring 4.3.7) 中使用自定义数据属性创建一个元素:
<input th:attr="data-customAttr=${item.getMyAttr()}" />
如果 item.getMyAttr() 的结果是“someVal”,则渲染的 HTML 为:
<input data-customAttr='someVal' />
但是,如果 item.getMyAttr() 的结果是空字符串,则 Thymeleaf 会完全丢弃自定义属性。呈现的 HTML 看起来像:
<input />
我需要知道自定义属性是否已定义且为空,或者是否缺失且未定义。根据这个讨论:空的 HTML5 数据属性是否有效? https://stackoverflow.com/questions/9729080/are-empty-html5-data-attributes-valid,空数据属性应该完全有效。
经过一番挖掘后,我遇到了以下测试用例,它似乎表明 Thymeleaf 无法渲染空数据属性,这就是它在渲染时间之前将它们丢弃的原因。下面的 Thymeleaf 片段渲染得很好:
<input th:attr="__${'data-customAttr=' + 'someVal'}__" />
虽然这两个都会抛出错误:
<!-- Throws: 'org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as assignation sequence' -->
<input th:attr="__${'data-customAttr=' + ''}__" />
<input th:attr="__${'data-customAttr'}__" />
这是 Thymeleaf 中的错误吗?任何帮助将不胜感激。我也很乐意提供任何其他相关信息。
编辑:这是我在相当大的应用程序中大量使用的功能。虽然我知道有几种解决方法,但它们都增加了我为了完成一项非常简单的任务而必须编写/维护的代码量。我希望有一个长期的解决方案,即使该解决方案是“这是一个错误,请报告它”。